类ViewController:UIViewController {
@IBOutlet weak var words: UILabel!
var positiveWords = ["dont give up","keep going","you can do that","your are strong"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func wordsButton(_ sender: Any) {
for w in positiveWords {
// show array in label
words.text = "\(w)"
}
}
}
当我单击按钮时,它仅显示一个单词,但是我想在单击时显示另一个单词,如何
您的问题有点含糊。但是这里有解决您问题的不同方法
//Wil generate different word every time you press the button
func wordsButton(_ sender: Any) {
words.text = positiveWords.randomElement(
}
如果您想一次添加整个数组,则>
func wordsButton(_ sender: Any) { for w in positiveWords { words.text! += "\(w) " } }
[如果您想一次添加一个
var displayedWords = o
func wordsButton(_ sender: Any) {
var totalWords = positiveWords.count
if displayedWords < totalWords {
label.text! += "\(positiveWords[displayedWords]) "
displayedWords += 1
}
}
显示给用户的单词是String的positiveWords数组的最后一个,因为您使用控制流For-In Loop来枚举数组并将当前元素设置为标签。