我有一个项目,其中放置了一个视图,一个用于隐藏视图的按钮,一个用于显示视图的按钮,一个标签和一个按钮(每次按该按钮,您得到的数字都不同于0)
@IBAction weak var myView: UIView!
@IBAction Weak var myLabel: UILabel!
var numbers: [Int] = [1, 7, 9, 6, 0, 3, 10, 45, 2, 83].shuffled()
override func viewDidLoad() {
super.viewDidLoad()
myView.isHidden = true
myLabel.text = "\(UserDefaults.standard.integer(forKey: "Key"))"
}
@IBAction func closeView(_ sender: Any) {
myView.isHidden = true
myLabel.text = 0
UserDefaults.standard.removeObject(forKey: "Key")
}
@IBAction func showView(_ sender: Any) {
myView.isHidden = false
}
@IBAction func addNumber(_ sender: Any) {
let oneNum = numbers.shuffled().first
UserDefaults.standard.set(oneNum, forKey: "Key")
myLabel.text = "\(UserDefaults.standard.integer(forKey: "Key"))"
}
我想要添加一个函数,如果标签显示的数字不同于0,该函数可以自动显示myView。该怎么办?
答案 0 :(得分:0)
我认为您想要的是这样的
@IBOutlet weak var myView: UIView!
@IBOutlet weak var myLabel: UILabel!
var numbers: [Int] = [1, 7, 9, 6, 0, 3, 10, 45, 2, 83].shuffled()
var currentNumber: Int {
didSet {
UserDefaults.standard.set(currentNumber, forKey: "currentNumberKey")
myLabel.text = "\(currentNumber)"
// Hide if number is 0, else show
myView.isHidden = currentNumber == 0
}
}
private func setNextNumber() {
currentNumber = numbers.shuffled().first!
}
override func viewDidLoad() {
super.viewDidLoad()
currentNumber = UserDefaults.standard.integer(forKey: "currentNumberKey")
}
@IBAction func closeView(_ sender: Any) {
currentNumber = 0
}
@IBAction func showView(_ sender: Any) {
myView.isHidden = false
}
@IBAction func addNumber(_ sender: Any) {
setNextNumber()
}
设置变量 currentNumber 将自动更新标签文本,并自动隐藏myView(如果currentNumber为零)或显示myView(如果currentNumber不为零)。
viewDidLoad 恢复状态。如果UIViewController消失并显示,状态将自动维护,因此 viewWillAppear / viewDidAppear 和< strong> viewWillDisappear / viewDidDisappear 。