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?
Here are the basic steps which will simplify things, in your case this would have to be repeated for each viewController.
Create one outlet for all your buttons:
@IBOutlet var myButtons: [UIButton]!
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
.
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!.
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With