0

Does anyone know how to make buttons change colors in swift? I have rectangle shaped buttons with text inside and a hollow background and I want the hollow space to change colors every 3 seconds or so. Can anyone help, I would greatly appreciate it!

3 Answers3

0

Can you try

 var counter = 0
 var pageChangeTimer: Timer?
 let colors = [UIColor.red,UIColor.green,,,,,,,,,] //,,,, set more

 pageChangeTimer = Timer.scheduledTimer( withTimeInterval: 3.0 , repeats: true) { [weak self] timer in 

    if counter == colors.count {
       counter = 0
    }
     self.btn.backgroundColor = colors[counter]  
    counter += 1      

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Extending @Sh_Khan's answer by generating random colors instead of an array of colors. I hope this helps:

Generating random colors

var counter = 0
var pageChangeTimer: Timer?

pageChangeTimer = Timer.scheduledTimer( withTimeInterval: 3.0 , repeats: true) { [weak self] timer in 

   if counter == colors.count {
      counter = 0
   }
   self.btn.backgroundColor = colors[counter]  
   counter += 1      
}


func getRandomColor() -> UIColor{
    //Generate between 0 to 1
    let red:CGFloat = CGFloat(drand48())   
    let green:CGFloat = CGFloat(drand48()) 
    let blue:CGFloat = CGFloat(drand48())  

    return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}
Vignan Sankati
  • 380
  • 5
  • 15
0

Try this

var net = Bool()

override func viewDidLoad() {
    super.viewDidLoad()
    net = true
    var timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)

}

// update method

@objc func update() {
// Something cool
if net == true {
    // changebtn is the outlet of UIButton
    changebtn.backgroundColor = UIColor.blue
    net = false
}else{
    changebtn.backgroundColor = UIColor.black
    net = true
}
}
chandra1234
  • 357
  • 6
  • 15
  • Can you tell me specifically where to place this code because it is not working. I can show you my code if neccessary – Ethan Sefchik May 13 '18 at 17:15
  • In viewDidLoad i created & called a timer method for every 3 seconds i checked it is working fine , the two colors are blinking for every 3 seconds. – chandra1234 May 14 '18 at 04:28