Apply custom UIButton styling to all Buttons
Create extensions for UIComponents
you wanna add common style.
Like in case of UIButton
extension UIButton {
open override func draw(_ rect: CGRect) {
//provide custom style
self.layer.cornerRadius = 10
self.layer.masksToBounds = true
}
}
Or create a subclass of UIButton
and provide all the styling u wanna apply and make sure your buttons extends from your custom class
class MyButton : UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.layer.cornerRadius = 10
self.layer.masksToBounds = true
}
}
You can make custom class using IBInspectable. so you can change from UI.====>
class NSCustomButton: UIButton {
@IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
self.clipsToBounds = true
self.layer.masksToBounds = true
}
}
@IBInspectable var cornerRadiusByHeight: Bool = false {
didSet {
layer.cornerRadius = self.frame.size.height/2
}
}
@IBInspectable var roundButton: Bool = false {
didSet {
layer.cornerRadius = self.frame.size.width / 2
self.clipsToBounds = true
self.layer.masksToBounds = true
}
}
@IBInspectable var shadowColor: UIColor = UIColor.clear {
didSet {
layer.shadowColor = shadowColor.cgColor
layer.masksToBounds = false
}
}
@IBInspectable var shadowOpacity: CGFloat = 0.0 {
didSet {
layer.shadowOpacity = Float(shadowOpacity.hashValue)
layer.masksToBounds = false
}
}
@IBInspectable var shadowRadius: CGFloat = 0.0 {
didSet {
layer.shadowOpacity = Float(shadowRadius.hashValue)
layer.masksToBounds = false
}
}
override internal func awakeFromNib() {
super.awakeFromNib()
}
}
You can use the UIAppearance api, like this:
UIButton.appearance().layer.cornerRadius = 4
UIButton.appearance().layer.shadowColor = UIColor.white.cgColor
UIButton.appearance().layer.shadowOffset = CGSize(width: 2, height: 2)
UIButton.appearance().layer.shadowRadius = 5
UIButton.appearance().layer.shadowOpacity = 0.5
UIButton.appearance().layer.masksToBounds = true
By using this, every UIButton on your application will have these visual properties set to what you've defined.
You can find more information about this API at https://developer.apple.com/documentation/uikit/uiappearance