【问题标题】:Button is not changing a value?按钮没有改变一个值?
【发布时间】:2020-09-30 04:52:08
【问题描述】:

我编写了一个代码来创建一个应该更改标签/文本字段的值的按钮。 我想制作一个俯卧撑应用程序,每次触摸屏幕上的按钮时,标签“您的分数:0”都会将分数增加 1,我也尝试将其作为文本字段。但它不起作用,什么都没有发生! 有人可以帮我吗?

标签代码:

func setupHelloWorld() {
        helloworld.textAlignment = .center
        helloworld.text = "Your Score: \(score)"
        helloworld.textColor = .gray
        helloworld.font = .boldSystemFont(ofSize: 30)
        self.view.addSubview(helloworld)
        

...

按钮代码:

func setUpNetButton() {
        nextButton.backgroundColor = .blue
        nextButton.setTitleColor(.white, for: .normal)
        nextButton.setTitle("Tap!", for: .normal)
        
        nextButton.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
        
        
        view.addSubview(nextButton)
        setUpNextButtonConstraints()
    }
    
    @objc func nextButtonTapped() {
        score += 1
}

【问题讨论】:

    标签: swift button uibutton uitextfield uilabel


    【解决方案1】:

    您必须手动更新标签的text 属性。仅仅因为您最初使用score 变量设置了它的文本,它不会自动响应变量值的任何更改,除非您明确设置新的标签文本。

    把你的代码改成这样就可以了:

    func setupHelloWorld() {
            helloworld.textAlignment = .center
            helloworld.textColor = .gray
            helloworld.font = .boldSystemFont(ofSize: 30)
            updateButtonText()
            self.view.addSubview(helloworld)
    }
    ...
    @objc func nextButtonTapped() {
            score += 1
            updateButtonText()
    }
    
    func updateButtonText() {
            helloworld.text = "Your Score: \(score)"
    }
    

    或者,您可以将didSet 观察者添加到您的score 属性并在每次为其分配新值时更改标签文本,而不是从nextButtonTapped() 方法调用updateButtonText。但是,您仍然需要在视图加载后更新标签的文本,因为在类的初始化期间不会调用 didSet。像这样的:

    private var score: Int = 0 {
        didSet {
            updateButtonText()
        }
    }
    
    override func viewDidLoad() {
        ...
        updateButtonText()
        ...
    

    【讨论】:

      【解决方案2】:

      这是因为您没有更改 helloworld 的值,将值分配给 更新分数后@objc函数nextButtonTapped()中的helloworld.text

      【讨论】:

        猜你喜欢
        • 2019-12-17
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 2021-01-22
        • 2015-07-15
        • 2013-01-03
        • 2017-04-29
        • 2016-11-13
        相关资源
        最近更新 更多