Search code examples
iosarraysswiftuibuttonuilabel

How to go through array with button press


I have an array that contains different information,

how can I iterate through the array with a button press? I have two buttons, and I need to allow one to move forward in the array and the back button to display the previous index.


  @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

}

I also added page control for better UX, but for now I'm just worried about learning how to even change the label through button Tap.

My guess would be to start the index at 0 which would be info1 and go from there. I can worry about saving index state later.

Any help is much appreciated.


Solution

  • Please check the below code you can do something like this to move your array forward and backward. Please add other checks according to your need.

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