代码的目的是在每次按下按钮时生成随机练习和重复次数(从数组中选择)。
但是,按钮只会在第一次按下时执行此操作,此后不会再执行。
问题:如何确保每次按下按钮时都会生成随机数量的重复和锻炼(从我的数组中选择)?
import UIKit
class ViewController: UIViewController
{
var clickCount = 0
let exercises = ["Push Ups", "Squats", "Burpees", "Sit Ups"]
let reps = ["5", "6", "7", "8", "9", "10"]
lazy var randomIndex1 = Int(arc4random() % UInt32(exercises.count))
lazy var randomIndex2 = Int(arc4random() % UInt32(reps.count))
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var excerciseType: UILabel!
@IBOutlet weak var repVolume: UILabel!
@IBAction func buttonPress(_ sender: UIButton) {
clickCount+=1
countLabel.text="You've Tapped \(clickCount) times"
excerciseType.text="\(exercises[randomIndex1])"
repVolume.text="\(reps[randomIndex2])"
}
}
最佳答案
通过将变量放入 buttonPress
方法中生成一个新值
所以,我会删除这两行
lazy var randomIndex1 = Int(arc4random() % UInt32(exercises.count))
lazy var randomIndex2 = Int(arc4random() % UInt32(reps.count))
并在 buttonPress 中设置这些值
@IBAction func buttonPress(_ sender: UIButton) {
clickCount+=1
let randomIndex1 = Int(arc4random() % UInt32(exercises.count))
let randomIndex2 = Int(arc4random() % UInt32(reps.count))
countLabel.text="You've Tapped \(clickCount) times"
excerciseType.text="\(exercises[randomIndex1])"
repVolume.text="\(reps[randomIndex2])"
}
现在它应该在每次按下按钮时生成一个新的随机值。正如 Leo 在评论中所说,由于我们每次都重新生成它们,因此它们应该是 let
而不是 var
注意
我最初提到了一些关于惰性变量的事情,因为这里似乎不需要它们。因此,如果您阅读评论并想知道人们在谈论什么;这是我最初所说的,这并不能真正帮助 OP 解决这个问题并且不清楚;所以我把它移到这里到这个注释:
A few things:
- a lazy var is actually a constant (or at least it gets treated like one in a lot of places)
关于ios - 需要按钮多次重复相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48176596/