简体   繁体   English

我不明白为什么这个if语句在Swift中不起作用

[英]I can't understand why this if statement doesn't work in Swift

My app involves two UILabels labelDisplay and labelStatus , one UIButton , buttonAddOne , and a variable numbers . 我的应用程序涉及两个UILabels labelDisplaylabelStatus ,一个UIButtonbuttonAddOne和一个可变numbers I can't understand why the labelStatus isn't being updated when numbers reaches 5. 我不明白为什么numbers达到5时labelStatus不能更新。

import UIKit

var numbers:Int = 0

class ViewController: UIViewController {

    // Declaration of the two labels
    @IBOutlet weak var labelDisplay: UILabel!
    @IBOutlet weak var labelStatus: UILabel!

    // Code for the "Add 1" button
    @IBAction func buttonAddOne(sender: AnyObject) {
        numbers = numbers + 1
        labelDisplay.text = "\(numbers)"
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if numbers == 5 {
            labelStatus.text = "Numbers variable is equal to 5! Hurray!"
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

I can't understand why the labelStatus isn't being updated when "numbers" reaches 5 我不明白为什么当“数字”达到5时labelStatus没有被更新

What would update it? 什么会更新呢? The code inside viewDidLoad ? viewDidLoad的代码? But viewDidLoad is called once, early, when the view controller gets its view; 但是,当视图控制器获取其视图时,会尽早调用一次viewDidLoad it will never be called again, so that code will never run again. 它永远不会被再次调用,因此代码将永远不会再次运行。

If you want to update labelStatus , why don't you do it in the same code that increments numbers ? 如果要更新labelStatus ,为什么不使用增加numbers的同一代码来完成呢?

@IBAction func buttonAddOne(sender: AnyObject) {
    numbers = numbers + 1
    labelDisplay.text = "\(numbers)"
    if numbers == 5 {
        labelStatus.text = "Numbers variable is equal to 5! Hurray!"
    }
}

The code you put in viewDidLoad is executed once, when the view is loaded - it isn't triggered every time numbers is updated. 加载视图后,放入viewDidLoad的代码将执行一次-每次更新numbers时都不会触发该代码。

To implement what you need, you should make number an instance property, and add a didSet observer: 要实现所需的功能,应将number为实例属性,并添加didSet观察器:

class ViewController: UIViewController {
    var numbers: Int = 0 {
        didSet {
            if numbers == 5 {
                labelStatus.text = "Numbers variable is equal to 5! Hurray!"
            }
        }
    }
    ...
}

The property observer is automatically executed when the property value is changed. 更改属性值后,将自动执行属性观察器。

For more info read Property Observers 有关更多信息,请阅读属性观察者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM