Alia.RK Alia.RK - 10 days ago 7
Swift Question

How do you Change the UILabel.text property to iterate through a array of strings and not hardcode an index

I have been trying to figure this out for days. I have searched everywhere its very simple but I'm so confused.

````

import UIKit

class ViewController: UIViewController {

var arrays = ["A", "b", "C", "D", "E", "F"]

@IBOutlet weak var ChangeText: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.


ChangeText.text = arrays[0]


}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


@IBAction func Button() {

ChangeText.text = arrays[1]
}


}

````

How do you change the text property which is an optional string in a xcode project to iterate through your array of strings without hardcoding the index of the array.

What I want is for the text in the label to change every time I press the button however given the value is Hardcoded it changes once and then that's it.

I've tried a for in loop and my own function, however I keep on getting errors and I don't know where to place my function or loop. So I've gotten rid of it.

Thank you for your patience and help

Answer

Just store the currentIndex as a property

import UIKit

class ViewController: UIViewController {

var arrays = ["A", "b", "C", "D", "E", "F"]
var currentIndex = 0

@IBOutlet weak var ChangeText: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    ChangeText.text = arrays[currentIndex]
}

@IBAction func Button() {
    currentIndex++
    if (currentIndex == arrays.count {
        currentIndex = 0
    }

    ChangeText.text = arrays[currentIndex]
}
}
Comments