我想创建一个标签,当我按下按钮时,标签会显示不同的单词。就像标签从数组中获取数据一样。我试过这段代码,但我不希望我的标签显示随机字样。我只想按顺序说出这些话。
clang++ -stdlib=libstdc++ ...
答案 0 :(得分:0)
您需要先创建一个数组:
let creatures = ["Cat", "Dog", "Bird", "Butterfly", "Fish"]
为您的标签添加IBOutlet
:
@IBOutlet weak var label: UILabel!
为您的按钮添加IBAction
:
@IBAction func updateLabelButtonTapped(_ sender: UIButton) {
// Get the index of a random element from the array
let randomIndex = Int(arc4random_uniform(UInt32(creatures.count)))
// Set the text at the randomIndex as the text of the label
label.text = creatures[randomIndex]
}
修改强>
如果您想按顺序显示单词,请在类中添加新属性以保存当前索引:
private var currentIndex = 0
并使用以下内容替换IBAction
:
@IBAction func updateLabelButtonTapped(_ sender: UIButton) {
label.text = creatures[currentIndex] // Set the text to the element at currentIndex in the array
currentIndex = currentIndex + 1 == creatures.count ? 0 : currentIndex + 1 // Increment currentIndex
}