Corner radius not showing on button in storyboard with @IBDesigable/@IBInspectable

不羁岁月 提交于 2019-11-28 05:04:22

问题


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.


回答1:


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:

And it also works in the running app.




回答2:


Try this one:

@IBDesignable
class CustomButton: UIButton {

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

}


来源:https://stackoverflow.com/questions/36759138/corner-radius-not-showing-on-button-in-storyboard-with-ibdesigable-ibinspectab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!