Ios 简单快速代码功能
我不熟悉Swift和移动编程。我正在做一个简单的申请。基本上,我需要从Ios 简单快速代码功能,ios,swift,uilabel,Ios,Swift,Uilabel,我不熟悉Swift和移动编程。我正在做一个简单的申请。基本上,我需要从@IBOutlet标签获取值 @IBOutlet var currentRoll: UILabel! 下面是我的一段代码。在变量totalDice中,我需要添加rolledDice中存储的随机数和currentRoll中的值,后者是UILabel。有没有办法获得打印在UILabel currentRoll中的值 @Paulw11是正确的,您不应该从UI检索这个值,但这是您可以做到的 在您的代码中,您刚刚更新了currentR
@IBOutlet
标签获取值
@IBOutlet var currentRoll: UILabel!
下面是我的一段代码。在变量totalDice中,我需要添加rolledDice中存储的随机数和currentRoll中的值,后者是UILabel。有没有办法获得打印在UILabel currentRoll中的值
@Paulw11是正确的,您不应该从UI检索这个值,但这是您可以做到的 在您的代码中,您刚刚更新了
currentRoll
,因此它的文本值将与rolledDice
相同——但我认为这不是您的意思。让我们将有问题的行向上移动一行,在使用新的滚动更新它之前,尝试获取currentRoll
的值
@IBAction func rollDice(sender: UIButton) {
// use let instead of var whenever you can
let rolledDice = Int(arc4random_uniform(6) + 1)
// initialize totalDice to the newly rolled value
var totalDice = rolledDice
// attempt to get a value from currentRoll - String.toInt() returns an Int?
if let currentDice = currentRoll.text.toInt() {
totalDice += currentDice
}
// update both labels
currentRoll.text = String(rolledDice)
totalDisplay.text = String(totalDice)
}
更好的做法是将数据与视图分开—将当前值存储在整数变量中,将新值添加到该变量中,然后更新文本字段使用标签的
text
属性并将其转换为整数。
@IBAction func rollDice(sender: UIButton) {
// use let instead of var whenever you can
let rolledDice = Int(arc4random_uniform(6) + 1)
// initialize totalDice to the newly rolled value
var totalDice = rolledDice
// attempt to get a value from currentRoll - String.toInt() returns an Int?
if let currentDice = currentRoll.text.toInt() {
totalDice += currentDice
}
// update both labels
currentRoll.text = String(rolledDice)
totalDisplay.text = String(totalDice)
}