如何通过按下按钮来遍历数组

时间:2020-05-01 03:14:10

标签: ios arrays swift uibutton uilabel

我有一个包含不同信息的数组,

如何通过按下按钮来遍历数组?我有两个按钮,我需要允许一个按钮在数组中向前移动,向后按钮以显示前一个索引。


  @IBOutlet weak var backButton: UIButton!
  @IBOutlet weak var nextButton: UIButton!



 @IBOutlet weak var infoLabel: UILabel!
 @IBOutlet weak var pageControl: UIPageControl!



Let infoArray = ["info1","info2","info3","info4"] 

@IBAction func nextTapped(_ sender: Any) {
// Change the label based on the selected index in array        

}

@IBAction func backTapped(_ sender: Any) {
 //Return to previous index and update label text

}

我还添加了页面控件以实现更好的UX,但现在我只是担心要学习如何通过按钮Tap来更改标签。

我的猜测是从0开始的索引为info1,然后从那里开始。我可以担心以后再保存索引状态。

我们非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

逻辑应该看起来像这样

let infoArray = ["info1","info2","info3","info4"]

func viewDidLoad() {
    pageControl.numberOfPages = infoArray.count
    pageControl.currentPage = 0
}

@IBAction func nextTapped(_ sender: Any) {
    // Change the label based on the selected index in array
    guard pageControl.currentPage + 1 < infoArray.count else {
        return
    }
    pageControl.currentPage += 1
}

@IBAction func backTapped(_ sender: Any) {
    //Return to previous index and update label text
    guard pageControl.currentPage - 1 >= 0 else {
        return
    }
    pageControl.currentPage -= 1
}

当用户点击页面控件以移至下一页或上一页时,该控件将发送valueChanged事件供委托处理。然后,委托可以评估currentPage属性以确定要显示的页面。页面控件只能向任一方向前进一页。

答案 1 :(得分:-2)

请检查以下代码,您可以执行以下操作来前后移动数组。请根据需要添加其他支票。

var i = 0
let infoArray = ["info1","info2","info3","info4"]

@IBAction func nextTapped(_ sender: Any) {
    // Change the label based on the selected index in array
   if i >= 0 && i < infoArray.count{
   dataLbl.text = infoArray[i]

    }
    if i > 3 {
        i = i-1
    } else  {
        i = i+1
    }

}

@IBAction func backTapped(_ sender: Any) {
    //Return to previous index and update label text
    if i >= 0 && i < infoArray.count-1 {
    dataLbl.text = infoArray[i]

    }
    if i < 0 {
        i = i+1
    } else  {
       i = i-1
    }

}