Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uibutton

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?

like image 902
Maxpower Avatar asked Feb 24 '15 17:02

Maxpower


2 Answers

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!.

like image 139
Patrick Avatar answered Oct 19 '22 22:10

Patrick


Go to your appDelegate, and change (this will only change the text color):

let buttonAppearance = UIButton.appearance()
    buttonAppearance.tintColor = UIColor(red: 1.0, green:1.0, blue:1.0, alpha:1.0)

This will attribute a text color wanted for all your buttons. You can do the same for navigationBar, tabBar etc....

like image 33
Labria Avatar answered Oct 19 '22 22:10

Labria