【问题标题】:swift 4 label that each time i hit the button the label shows a different word [closed]swift 4标签,每次我按下按钮时,标签都会显示一个不同的单词[关闭]
【发布时间】:2018-06-11 07:29:09
【问题描述】:

我想创建一个标签,当我点击按钮时,标签会显示不同的单词。就像标签从数组或其他东西中获取数据一样。我尝试了这段代码,但我不希望我的标签显示随机单词。我只想要单词的顺序。

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

【问题讨论】:

  • 您的问题既过于模糊又过于宽泛。萌的回答和任何人一样好。
  • 贴出你已经尝试过的代码。

标签: ios swift


【解决方案1】:

你需要先创建一个数组:

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
}

【讨论】:

  • 我正在尝试按顺序显示单词而不是随机的,你能帮帮我吗?
  • @Dairon 检查我更新的答案。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
相关资源
最近更新 更多