Kobe Kobe - 2 months ago 31
Swift Question

Toggle between three states with UIButton

I have a

UIButton
for which I want to switch the title and color when I press it. The button should have three states: daily, monthly and yearly.

Right now I have this solution which doesn't seem that elegant:

if sender.currentTitle == "Daily" {
sender.setTitle("Monthly", for: .normal)
sender.setTitleColor(UIColor(hex: "FB967F"), for: .normal)
} else if sender.currentTitle == "Monthly" {
sender.setTitle("Yearly", for: .normal)
sender.setTitleColor(UIColor(hex: "A395CE"), for: .normal)
} else if sender.currentTitle == "Yearly" {
sender.setTitle("Daily", for: .normal)
sender.setTitleColor(UIColor(hex: "75CFF8"), for: .normal)
}


Is there a more convenient way to do this in Swift ?

Answer

Declare a counter variable and two arrays

var counter = 0
let titleArray = ["Daily", "Monthly", "Yearly"]
let colorArray = ["FB967F", "A395CE", "75CFF8"]

then increment the counter (keep it in range 0...2 via the modulo operator) and get the title and color values from the arrays

counter = (counter + 1) % titleArray.count
sender.setTitle(titleArray[counter], for: .normal)
sender.setTitleColor(UIColor(hex: colorArray[counter]), for: .normal)