How can I make a button have a rounded border in Swift?

后端 未结 15 2101
庸人自扰
庸人自扰 2021-01-29 17:50

I\'m building an app using swift in the latest version of Xcode 6, and would like to know how I can modify my button so that it can have a rounded border that I could adjust mys

15条回答
  •  生来不讨喜
    2021-01-29 18:05

    You can subclass UIButton and add @IBInspectable variables to it so you can configure the custom button parameters via the StoryBoard "Attribute Inspector". Below I write down that code.

    @IBDesignable
    class BHButton: UIButton {
    
        /*
        // Only override draw() if you perform custom drawing.
        // An empty implementation adversely affects performance during animation.
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
        */
    
        @IBInspectable lazy var isRoundRectButton : Bool = false
    
        @IBInspectable public var cornerRadius : CGFloat = 0.0 {
            didSet{
                setUpView()
            }
        }
    
        @IBInspectable public var borderColor : UIColor = UIColor.clear {
            didSet {
                self.layer.borderColor = borderColor.cgColor
            }
        }
    
        @IBInspectable public var borderWidth : CGFloat = 0.0 {
            didSet {
                self.layer.borderWidth = borderWidth
            }
        }
    
        //  MARK:   Awake From Nib
    
        override func awakeFromNib() {
            super.awakeFromNib()
            setUpView()
        }
    
        override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
            setUpView()
        }
    
        func setUpView() {
            if isRoundRectButton {
                self.layer.cornerRadius = self.bounds.height/2;
                self.clipsToBounds = true
            }
            else{
                self.layer.cornerRadius = self.cornerRadius;
                self.clipsToBounds = true
            }
        }
    
    }
    

提交回复
热议问题