来回带有两个按钮的字符串数组

时间:2018-05-16 01:38:37

标签: swift

我想在viewdidload()上显示第一项,然后让用户转到数组中的下一项,并且可以选择返回并禁用后退按钮,如果它是第一个索引并禁用按钮,如果它最后一个索引。这是我的代码

@IBAction func back(_ sender: Any) {
   c -= 1

   if c == thkrArray.count{
       nextButton.isEnabled = false
   }
   if c == 0{
       backButton.isEnabled = false
   }
   let thkr: String = thkrArray[c]
   Text1.text = thkr

}

@IBAction func A2(_ sender: Any) {
   c += 1

   if c == thkrArray.count{
       nextButton.isEnabled = false
   }
   if c == 0 {
       backButton.isEnabled = false
   }
   if c > 0{
       backButton.isEnabled = false
   }
   let thkr: String = thkrArray[c]
   Text1.text = thkr

}

1 个答案:

答案 0 :(得分:0)

实现此目的的最简单方法是向c添加观察者:

var c: Int = 0 {
    didSet {
        Text1.text = thkrArray[c]

        backButton.isEnabled = c > 0
        nextButton.isEnabled = c < thkrArray.count - 1
    }
}

@IBAction func back(_ sender: Any) {
    c -= 1
}

@IBAction func A2(_ sender: Any) { // isn't this `next`?
    c += 1
}

override func viewDidLoad() {
    super.viewDidLoad()
    c = 0
}