Change the color of UIButton in IBOutletCollection

后端 未结 2 847
终归单人心
终归单人心 2020-12-20 09:29

I have an IBOutletCollection of UIButton:

@IBOutlet var buttons: [UIButton]!

and a function for a tap:

@IBAction func butto         


        
相关标签:
2条回答
  • 2020-12-20 09:49

    Try this code:

    @IBOutlet var buttons: [UIButton]!
    var lastTappedButton: UIButton?
    
    @IBAction func button_Tap(_ sender: UIButton) {
    
        for button in buttons {
            if let lastTappedButton = lastTappedButton, lastTappedButton != sender {
                button.backgroundColor = .white
            }
            if button.tag == sender.tag { 
                button.backgroundColor = .blue 
                lastTappedButton = button
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-20 09:55

    For this to work

    1- All buttons should be connected to

     @IBOutlet var buttons: [UIButton]!
    

    2- All buttons should be connected to

    @IBAction func button_Tap(_ sender: UIButton) 
    

    3- Every button should have a different tag for example 0,1,2

    4- You can use this

    @IBAction func button_Tap(_ sender: UIButton) {
      self.buttons.forEach { $0.backgroundColor = $0 === sender ? .blue : .white  }
    }
    

    Result

    0 讨论(0)
提交回复
热议问题