Apply custom UIButton styling to all Buttons

vandernat.p picture vandernat.p · Sep 16, 2017 · Viewed 9k times · Source

I want to apply some styling to all my viewcontrollers from multiple storyboards. I have many viewcontrollers so applying the styling to every viewcontroller sounds rather silly. I want to do it in the most code lean way as possible. I was thinking to do it in the AppDelegate file since you can also change your navigationcontroller styling there, but so far no succes. Not even in the slightest way.

So does anyone know how I can do this?

I am using Swift for the app.

The following styling principles have to be applied: cornerRadius, shadowColor, shadowOffset, shadowRadius, shadowOpacity, maskToBounds.

Answer

Sandeep Bhandari picture Sandeep Bhandari · Sep 16, 2017

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
      }

}