-1

I'm looking for a way to change background color only for buttons that have the same text. So I created (at this time only 2) IBOutletCollections and 1 IBAction to test. But I have 27 different button numbers to code... or do I need to create 27 Outlet Collections and 27 Actions?

class SecondViewController: UIViewController {


@IBOutlet var button1color: [UIButton]!
@IBOutlet var button2color: [UIButton]!

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

}


@IBAction func bouton1(_ sender: UIButton) {
    for button in self.button1color {
        if button.backgroundColor == nil {
        button.backgroundColor = UIColor(displayP3Red: 1, green: 1, blue: 0.5, alpha: 0.8)
        } else {
            button.backgroundColor = nil
        }
    }

}

Is there a way to create a function to avoid typing 27 times the same code for each case?

For more informations, feel free to ask me!

Thank you for your help.

Quentin F.
  • 17
  • 2

1 Answers1

2

I'm looking for a way to change background color only for buttons that have the same text

I understand it like this: You need collection of buttons and when some button from this collection is pressed, you want to change color for all buttons from collection which have the same text (title when we're speaking about UIButton)


So you can have just one collection for all buttons. Link them to this collection

@IBOutlet var buttons: [UIButton]!

enter image description here

and also you can have just one action for all buttons. Also link them to this action. Then when button is pressed, change backgroundColor of button which has the same title as button which's been pressed

@IBAction func buttonPressed(_ sender: UIButton) {
    for button in buttons where button.currentTitle == sender.currentTitle {
        button.backgroundColor = UIColor(displayP3Red: 1, green: 1, blue: 0.5, alpha: 0.8)
    }
}

enter image description here

Robert Dresler
  • 10,580
  • 2
  • 22
  • 40