01/08/2019, 16:50

Custom UIButton

1. Create extensions for UIComponents you wanna add common style. extension UIButton { open override func draw(_ rect: CGRect) { //provide custom style self.layer.cornerRadius = 10 self.layer.masksToBounds = true } } 2. Create a subclass of UIButton and provide all the styling u wanna apply ...

1. Create extensions for UIComponents you wanna add common style.

extension UIButton { open override func draw(_ rect: CGRect) { //provide custom style self.layer.cornerRadius = 10 self.layer.masksToBounds = true } }

2. 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

}

3. Use the UIAppearance api

UIButton.appearance().layer.cornerRadius = 4 UIButton.appearance().layer.shadowColor = UIColor.white.cgColor UIButton.appearance().layer.shadowOffset = CGSize(awidth: 2, height: 2) UIButton.appearance().layer.shadowRadius = 5 UIButton.appearance().layer.shadowOpacity = 0.5 UIButton.appearance().layer.masksToBounds = true

4. 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.awidth / 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()
}

}

0