Ios swift 4标签,每次我按下按钮,标签上都会显示不同的单词

Ios swift 4标签,每次我按下按钮,标签上都会显示不同的单词,ios,swift,Ios,Swift,我想创建一个标签,当我按下按钮时,标签会显示不同的单词。就像标签从数组或其他地方获取数据一样。我试过这个代码,但我不想让我的标签显示随机单词。我只想把话讲清楚 import UIKit class ViewController: UIViewController { @IBOutlet weak var funFactLabel: UILabel! @IBOutlet weak var showButton: UIButton! var factProvider =

我想创建一个标签,当我按下按钮时,标签会显示不同的单词。就像标签从数组或其他地方获取数据一样。我试过这个代码,但我不想让我的标签显示随机单词。我只想把话讲清楚

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var funFactLabel: UILabel!
    @IBOutlet weak var showButton: UIButton!

    var factProvider = FactProvider()

    override func viewDidLoad() {
        super.viewDidLoad()

        funFactLabel.text = factProvider.randomFact()
    }

    @IBAction func showFact() {
        funFactLabel.text = factProvider.randomFact()

        let newColor = BackgroundColorProvider.randomColor()
        view.backgroundColor = newColor
        showButton.tintColor = newColor
    }
}

您需要先创建一个数组:

let creatures = ["Cat", "Dog", "Bird", "Butterfly", "Fish"]
并为您的标签添加一个
IBOutlet

@IBOutlet weak var label: UILabel!
并为按钮添加一个
iAction

@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
并将您的
iAction
替换为以下内容:

@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
}

你的问题既含糊又宽泛。Moe的答案和任何答案一样好。发布你已经尝试过的代码。我正在尝试按顺序显示单词,而不是随机。你能帮我吗?@Dairon检查我更新的答案。祝你好运!