我有一个按钮的自定义类. import UIKit@IBDesignableclass CustomButton: UIButton { @IBInspectable var cornerRadiusValue: CGFloat = 10.0 { didSet { setUpView() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)
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 } }
但是角落半径没有显示在故事板中的按钮上.
我理解@IBInspectable只允许您更改检查器面板中的值.我想这不是我想要的.
当我创建一个具有该类的按钮时,我希望角落半径只显示在故事板中.我认为这就是@IBDesignable的作用.
您的代码在IB中崩溃,因此可设计性失败.以下是更简单的代码:@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 } }
现在按钮既可检测又可设计:
它也适用于正在运行的应用程序.