Highlighting a button that gets pressed and unhighlighting the non pressed buttons SWIFT

Viewed 252

I have three buttons that connect to the same IBAction. They all have their own out looks. I found out how to make the button become highlighted when they are pressed and unhighlighted when the user presses another button. Is their a better way to write the code? Here is what I am using:

@IBAction func tipChanged(_ sender: UIButton) {
    zeroPCTButton.isSelected = false 
    tenPCTButton.isSelected = false 
    twentyPCTButton.isSelected = false 
    sender.isSelected = true
}

The reason why I am asking is because I could make an application that has a thousand buttons and I don't want to brute force statements a thousands times

2 Answers

We can unhighlight the non pressed UIButton in the following way,

@IBAction func buttonAction(_ sender: Any) {

        let the_tag = (sender as AnyObject).tag;
        let button = self.view.viewWithTag(the_tag!) as? UIButton
        button?.isSelected = true
        button?.backgroundColor = UIColor.white
        button?.setTitleColor(UIColor.black, for: .normal)

        // Create a list of all tags
        let allButtonTags = [1, 2, 3, 4, 5]
        let currentButtonTag = (sender as AnyObject).tag

           allButtonTags.filter { $0 != currentButtonTag }.forEach { tag in
               if let button = self.view.viewWithTag(tag) as? UIButton {
                   // Deselect/Disable these buttons
                   button.backgroundColor = #colorLiteral(red: 0.80803, green: 0.803803, blue: 0.805803, alpha: 1)
                   button.setTitleColor(UIColor.darkGray, for: .normal)
                   button.isSelected = false

               }
           }
    }

Let's Imagine you have 1000 buttons, You need to Implement some loop to do all the action related Button (Create,Add constraints, click events).Create UIButton Array for store your buttons.

var buttons:[UIButton] = []

Add buttons to this array when you create buttons

for buttonIndex in 1...1000 {
    // your other stuff to create, add constraints to button
    button.tag = buttonIndex
    buttons.append(button)
}

Now you can easily achieve your object.

@IBAction func tipChanged(_ sender: UIButton) {
    buttons.forEach({$0.isSelected = $0.tag == sender.tag})
    view.layoutIfNeeded()
}
Related