Manstof Manstof - 4 years ago 244
Swift Question

Swift: UIButton Customization

I would like to move the code to customize

UIButtons
out of my
viewcontroller
classes as a best practice. The code I have below is to add a white border to
UIButtons
and I would like to easily call it on buttons throughout my project.

//White Border
let passwordBorder = CALayer()

let width = CGFloat(5.0)

passwordBorder.borderColor = UIColor.whiteColor().CGColor

passwordBorder.frame = CGRect(x: 0, y: 0, width: passwordField.frame.size.width, height: passwordField.frame.size.height)

passwordBorder.borderWidth = width

passwordField.layer.addSublayer(passwordBorder)

passwordField.layer.masksToBounds = true


How would I put this code into a helper function so I could call it easily?

I am new to coding and am having trouble with helper functions on anything
UI
. Thanks!

Answer Source

Take a look at Swift's Extensions. You could pretty easily do something like

extension UIButton {
      func setPasswordBorderColor(borderColor: UIColor) {
        //White Border
        let passwordBorder = CALayer()

        let width = CGFloat(5.0)

        passwordBorder.borderColor = borderColor.CGColor

        passwordBorder.frame = CGRect(x: 0, y: 0, width:  self.frame.size.width, height: self.frame.size.height)

        passwordBorder.borderWidth = width

        self.layer.addSublayer(passwordBorder)

        self.layer.masksToBounds = true
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download