【发布时间】:2018-05-22 05:24:20
【问题描述】:
我有一个在整个应用程序中重复出现的按钮,因此我创建了一个子类以避免每次都必须设置所有基本属性。
我可以设置背景颜色、文本颜色、圆角。
但是,当我尝试设置默认标题时,事情就崩溃了——不是“按钮”。 在 Interface Builder 中,它会忽略标题,但也会忽略字体颜色,这在我不设置标题时有效。
如果我运行应用程序,一切看起来都很好,但使用 Interface Builder 的一大要点是省去不断运行应用程序以检查基本 UI 布局的步骤。
这是子类。 请注意,如果您注释掉 2 个 setTitle 行,按钮会显示正确的文本颜色(白色)。
import UIKit
@IBDesignable class ContinueButton: UIButton {
@IBInspectable var titleColour: UIColor = .white {
didSet {
setTitleColor(titleColour, for: .normal)
}
}
@IBInspectable var bgColour: UIColor = UIColor.gray {
didSet {
backgroundColor = bgColour
}
}
@IBInspectable var buttonTitle: String = "Continue" {
didSet {
setTitle(buttonTitle, for: .normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setAttributes()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setAttributes()
}
public func setAttributes() {
setTitleColor(titleColour, for: .normal)
backgroundColor = bgColour
setTitle(buttonTitle, for: .normal)
}
override public func layoutSubviews() {
super.layoutSubviews()
setAttributes()
layer.cornerRadius = 0.5 * bounds.size.height
clipsToBounds = true
}
}
ps,我的主要目标是创建一个可重用的自定义按钮,负责设置一堆默认值。如果有更好的方法来实现这一点,我会很高兴听到这个消息 - 特别是如果它可以通过视觉而不是通过代码来完成。
感谢您提供的任何建议,
-妮可
【问题讨论】:
-
首先,你为什么要重命名东西?使用
backgroundColor等。不要重新发明轮子!(您已经继承了UIButton。)其次,您是否将 IB(或情节提要)按钮设置为实际ContinueButton?最后,如果您需要我所说的示例,请参考我对此的回答:stackoverflow.com/questions/42041809/… 基本上,子类,设置 IBDesignable/IBInspectable,并公开 - 使用已经建立的属性 - 你需要什么。 -
我正在重命名,因为(根据错误消息)您不能覆盖变量然后为其设置初始值。您展示的示例访问 Layer 中的相同命名变量,而不是直接在 UIButton 中。
-
是的,我确实设置了按钮类 - 没有它,最终结果看起来不像我的示例图片。澄清一下 - 我试图使用子类来避免在 IB 中创建的每个按钮中设置所有属性。我在图片中展示的示例仅使用了子类设置的属性 - 我没有在 IB 中自定义该按钮。
标签: ios swift uibutton interface-builder subclass