You can do this via UIAppearance, which is a proxy that allows you to configure properties for all objects of a UIKit
class.
Firstly, as UIAppearance
works on properties on the UIView
itself and the ones you want to control are on the button layer, you need to expose this to the appearance:
@objc extension UIButton {
dynamic var borderColor: UIColor? {
get {
if let cgColor = layer.borderColor {
return UIColor(CGColor: cgColor)
}
return nil
}
set { layer.borderColor = newValue?.CGColor }
}
dynamic var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
dynamic var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
}
in Swift
, the dynamic
keyword instructs the compile to generate getters and setters for the property, so that UIAppearance
that identify it as configurable, (see this SO question, and Apple's documentation for more details).
You can then set the properties on the ui appearance of the UIButton
class:
UIButton.appearance().borderColor = UIColor.grayColor();
UIButton.appearance().borderWidth = 2;
UIButton.appearance().cornerRadius = 20;
You should do the configuration during the application startup, as the appearance changes apply when the view is added to the window (see the note on the UIAppearance
documentation).
If you want to give these default properties only for some buttons in your class, you can subclass UIButton
, and use the appearance on that class instead of UIButton
. For example:
class MyButton: UIButton {}
...
MyButton.appearance().borderColor = UIColor.grayColor();
MyButton.appearance().borderWidth = 2;
MyButton.appearance().cornerRadius = 20;
will apply the styling only to buttons of the MyButton
class. This allows you to define different look&feel for buttons in your class by simply subclassing UIButton
and working on the appearance of the subclass.