Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply custom UIButton styling to all Buttons

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.

like image 237
vandernat.p Avatar asked Sep 16 '17 17:09

vandernat.p


People also ask

How do you highlight a button when it is clicked Swift?

In the identity inspector in the right corner there is a filed named "class" there type "HighlightedButton" and press enter. Now your button will change color to red when it is highlighted and back to green when you release the button. You can change to any color you want.

How do I code buttons in Xcode?

Create a new project and open up Main. storyboard . Search for a button in this dialog and drag the Button object onto your storyboard screen. You can then modify the styles and text of the button to suit your liking.


1 Answers

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
      }

}
like image 109
Sandeep Bhandari Avatar answered Sep 30 '22 03:09

Sandeep Bhandari