为什么当我按下按钮时UILabel没有改变?

时间:2019-12-03 18:37:13

标签: swift

通过在我的应用程序中按一个按钮,变量的值下降3。尽管这种情况没有任何问题,但使用字符串插值显示变量作为其文本的标签(label.text)不能反映更改

如何做到这一点,所以按下按钮会更改UILabel的值?

import UIKit

class ViewController: UIViewController {

var token = 5

let theButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("button", for: .normal)
    button.backgroundColor = .systemPink
    button.addTarget(self, action: #selector(theButtonPressed), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

@objc func theButtonPressed() {
    if token >= 3 {
        token -= 3
    print("ok done")
    } else {
    print("nope")
    }
}

lazy var tokenLabel: UILabel = {
    let label = UILabel()
    label.text = "\(token)"
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()


override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .systemBlue

    view.addSubview(tokenLabel)
    view.addSubview(theButton)

    theButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
    theButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
    theButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    theButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    tokenLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 60).isActive = true
    tokenLabel.heightAnchor.constraint(equalToConstant: 300).isActive = true
    tokenLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
    tokenLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}    
}

1 个答案:

答案 0 :(得分:0)

按下按钮时,您需要更新标签的文本。

@objc func theButtonPressed() {
    if token >= 3 {
        token -= 3
        print("ok done")
        tokenLabel.text = "\(token)" // <- update
    } else {
        print("nope")
    }
}

或者,您可以观察属性token并在设置新值时更改标签。

var token = 5 {
    didSet {
        tokenLabel.text = "\(token)"
    }
}

@objc func theButtonPressed() {
    if token >= 3 {
        token -= 3
        print("ok done")
    } else {
        print("nope")
    }
}