gpt4 book ai didi

button - Swift-如何让按钮在每次点击时刷新?

转载 作者:行者123 更新时间:2023-11-30 10:19:48 25 4
gpt4 key购买 nike

我似乎无法弄清楚如何在快速按下 UIButton 时重复功能 block 。这是我所拥有的:

class CoinFlip: UIViewController {
@IBOutlet var resultLabel: UILabel!
var randomNumber = (Int(arc4random_uniform(2)))
@IBAction func tossButton(sender: UIButton) {
if randomNumber == 0 {
resultLabel.text = "Heads!"
}
else if randomNumber == 1 {
resultLabel.text = "Tails!"
}
}
}

当在应用程序中按下按钮时,它会选择一个随机数字。如果我再次点击它,它会显示相同的数字。我该怎么做才能每次点击按钮时它都会刷新?

最佳答案

    var randomNumber = 0

@IBAction func tossButton(sender: UIButton) {
randomNumber = Int(arc4random_uniform(2))
if randomNumber == 0 {
resultLabel.text = "Heads!"
} else {
resultLabel.text = "Tails!"
}
}

您还可以创建只读计算属性,如下所示:

Read-Only Computed Properties

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

NOTE

You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.

You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:

    var headsTails:Bool {
return Int(arc4random_uniform(2)) == 1 ? true : false
}

if headsTails {
println("Heads")
} else {
println("Tails")
}

println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)
println(headsTails)

关于button - Swift-如何让按钮在每次点击时刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27682776/

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