如何按下按钮上的数组中的项目?

时间:2017-05-24 20:31:08

标签: ios arrays swift

让我们说有一个数组:

var items = ["first", "second", "third"]

每次按下按钮,它都应该转到数组中的下一个项目。

 @IBAction func buttonPressed(_ sender: Any) {
label.text = currentItem
      }

我尝试过使用for in循环,但它只是一次遍历整个数组:

for item in items {
print(item)
}

如何拥有它所以它一次只能通过数组一个项目?

3 个答案:

答案 0 :(得分:1)

跟踪计数器。应该很直接。类似的东西:

var items = ["first", "second", "third"]
var currentIndex: Int = 0 {
    didSet {
        currentIndex = currentIndex % items.count
    }
}

@IBAction func buttonPressed(_ sender: Any) {
    label.text = items[currentIndex]
    currentIndex += 1
}

答案 1 :(得分:1)

您想要的是为您正在查看的索引维护变量。然后你可以通过它的索引引用该项目。你要确保你不会走出界限。这可以通过模数轻松完成。

E.g。

var items = ["first", "second", "third"]
var index = 0

@IBAction func buttonPressed(_ sender: Any) {
        label.text = items[index]
        index = (index + 1) % items.count
}

编辑:二元鸭嘴兽的答案比我的好[/ p>]

答案 2 :(得分:0)

保持变量居住在那里(并使代码混乱)的一种方法是获取当前对象的索引并返回下一个或第一个,如下所示:

@IBAction func buttonPressed(_ sender: Any) {
    guard let text = label.text, let index = items.index(of: text) else { return }
    label.text = index + 1 < items.count ? items[index + 1] : items[0]
}

这样就可以让你的属性变得更干净了,而且我认为它让你的代码更容易理解。