gpt4 book ai didi

ios - Swift 3 : How do I increase a variable being displayed as a UILabel, 然后以编程方式更新 UILabel?

转载 作者:行者123 更新时间:2023-11-28 11:01:41 24 4
gpt4 key购买 nike

我有一个应该显示分数的标签,以及一个应该在每次按下时增加该分数的按钮。我的问题是无论我把函数放在哪里都会出错。

如果我在 viewDidLoad 类之上有一个函数,那么我会得到一个错误,因为它出现在我的标签之前,但是如果我把它放在 viewDidLoad 中的任何地方,我会得到一个错误,因为我不能调用本地函数,如果我把它之后的任何地方,然后我调用函数的按钮出现在函数之前。

我应该把这些东西放在哪里?有没有更好的方法一起做这一切?这本来应该如此简单......

import UIKit

class ViewController: UIViewController {

let phrase = "Your score: "
var increasingNum = 0

func scoreGoUp (sender: UIButton){

increasingNum += 1
label.text = "\(phrase) \(increasingNum)"

}

override func viewDidLoad() {
super.viewDidLoad()

let label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: self.view.frame.size.height / 2 - 10, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)

let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: 100, width: 300, height: 50))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)
self.view.addSubview(button)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

}

最佳答案

我已经修改了你的代码。希望对您有所帮助。

class ViewController: UIViewController {

var label:UILabel!
let phrase = "Your score: "
var increasingNum = 0


override func viewDidLoad() {
super.viewDidLoad()

label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: self.view.frame.size.height / 2 - 10, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)

let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: 100, width: 300, height: 50))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)

self.view.addSubview(button)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

func scoreGoUp (sender: UIButton){

increasingNum += 1
label.text = "\(phrase) \(increasingNum)"

}
}

Here is the output

关于ios - Swift 3 : How do I increase a variable being displayed as a UILabel, 然后以编程方式更新 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com