Corner radius not showing on button in storyboard

2020-02-13 01:56发布

I have this custom class for a button.

import UIKit

@IBDesignable
class CustomButton: UIButton {

    @IBInspectable var cornerRadiusValue: CGFloat = 10.0 {
        didSet {
            setUpView()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 10.0
    }

    override func awakeFromNib() {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.layer.cornerRadius = 10.0
    }

}

But the corner radius is not showing on the button in the storyboard.

I understand @IBInspectable just allows you to change the value in the inspector panel. I guess thats not what I am looking for.

I would like the corner radius to just show in storyboard when I create a button with that class. Which I thought that's what @IBDesignable does.

3条回答
欢心
2楼-- · 2020-02-13 02:16

Try this one:

@IBDesignable
class CustomButton: UIButton {

    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }

}
查看更多
霸刀☆藐视天下
3楼-- · 2020-02-13 02:26

Your code is crashing in IB, so designability fails. Here is much simpler code that works:

@IBDesignable
class CustomButton: UIButton {
    @IBInspectable var cornerRadiusValue: CGFloat = 10.0 {
        didSet {
            setUpView()
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }
    func setUpView() {
        self.layer.cornerRadius = self.cornerRadiusValue
        self.clipsToBounds = true
    }
}

Now the button is both inspectable and designable:

enter image description here

And it also works in the running app.

查看更多
在下西门庆
4楼-- · 2020-02-13 02:27

Here's a better solution than the accepted answer:

@IBDesignable
class DesignableButton: UIButton {

    @IBInspectable private var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.masksToBounds = newValue > 0
            layer.cornerRadius = newValue
        }
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setNeedsDisplay()
    }

}

It uses a computed property to avoid duplicating state with a stored property.

查看更多
登录 后发表回答