Maxpower Maxpower - 17 days ago 8
iOS Question

Can I change the properties of all the buttons in my Swift app?

I have a Swift app that navigates through many view controllers, all with similar appearances. There are buttons in every view controller for which I have NOT created IBOutlet properties (they all just trigger segues via Interface Builder).

Is there an easy way to change the background color or text color of all the buttons in the app, without changing it for every button in IB, or creating an IBOutlet for each button?

Answer

Here are the basic steps which will simplify things, in your case this would have to be repeated for each viewController.

  1. Create one outlet for all your buttons:

    @IBOutlet var myButtons: [UIButton]!
    
  2. Connect (drag) this outlet with each of the buttons on the view. Click on each of the buttons in your interface and checkout "Referencing Outlet Collections" found on in the connections inspector (the last button with the arrow in the circle). Notice that they should all by linked to myButtons.

  3. Style your buttons in a for loop:

    for button in self.myButtons {
        button.backgroundColor = UIColor.clearColor()
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.greenColor().CGColor
    }
    

To make this work application wide, you have a few options to investigate. You could use constants so at least when you wish to change the style, you only have to modify one file: Constants in Objective-C, Global constants file in Swift.

Alternatively there are several ways to make a function public. I will try and get some example code, but a class called buttonStyle could be important into each viewController and called in the for loop: [buttonStyle styleButton:button]. The styleButton function would set the style (I haven't tested anything out for this).

Checkout this answer by @zisoft: How to loop through Outlets of a UIViewController with Swift, it is a log more detailed!.

Comments