Change UIButton BorderColor in Storyboard

后端 未结 7 1334
南笙
南笙 2020-12-12 14:31

I Set CornerRadius and BorderWidth for UIbutton in User Defined Runtime Attributes. Without adding layer.borderColor it works Well and Display border in bla

7条回答
  •  天命终不由人
    2020-12-12 15:25

    Swift 4, Xcode 9.2 - Use IBDesignable and IBInspectable to build custom controls and live preview the design in Interface Builder.

    Here is a sample code in Swift, place just below the UIKit in ViewController.swift:

    @IBDesignable extension UIButton {
    
        @IBInspectable var borderWidth: CGFloat {
            set {
                layer.borderWidth = newValue
            }
            get {
                return layer.borderWidth
            }
        }
    
        @IBInspectable var cornerRadius: CGFloat {
            set {
                layer.cornerRadius = newValue
            }
            get {
                return layer.cornerRadius
            }
        }
    
        @IBInspectable var borderColor: UIColor? {
            set {
                guard let uiColor = newValue else { return }
                layer.borderColor = uiColor.cgColor
            }
            get {
                guard let color = layer.borderColor else { return nil }
                return UIColor(cgColor: color)
            }
        }
    }
    

    If you go to the Attributes inspectable of the view, you should find these properties visually, edit the properties:

    The changes are also reflected in User Defined Runtime Attributes:

    Run in build time and Voila! you will see your clear rounded button with border.

提交回复
热议问题