[英]How to set a default title in UIButton subclass that works in Interface Builder (Xcode 9)
I have a button that repeats throughout my app, so I created a subclass to avoid having to set all the basic properties every time.我有一个在整个应用程序中重复的按钮,因此我创建了一个子类以避免每次都必须设置所有基本属性。
I am able to set the background colour, the text colour, round the corners.我可以设置背景颜色、文本颜色、圆角。
However, things fall apart when I try to set a default title - something other than "Button".但是,当我尝试设置默认标题时,事情就分崩离析了——不是“按钮”。 In Interface Builder it ignores the title, but it also then ignores the font colour, which works when I don't set the title.
在 Interface Builder 中,它会忽略标题,但也会忽略字体颜色,这在我未设置标题时有效。
If I run the app, it all looks fine, but one major point of using Interface Builder is to save the step of constantly running the app to check basic UI layout.如果我运行该应用程序,一切看起来都不错,但使用 Interface Builder 的一个主要目的是省去不断运行应用程序以检查基本 UI 布局的步骤。
Here is the subclass.这是子类。 Note that if you comment out the 2 setTitle lines, the button shows the correct text colour (white).
请注意,如果您注释掉 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, My main objective is to create a reusable custom button that takes care of setting a bunch of defaults. ps,我的主要目标是创建一个可重用的自定义按钮,负责设置一堆默认值。 If there's a better way to achieve that, I'd be very happy to hear that - especially if it could be done visually rather than through code.
如果有更好的方法来实现这一点,我会很高兴听到这个消息 - 特别是如果它可以通过视觉而不是通过代码来完成。
Thanks for any advice you can give,感谢您提供的任何建议,
-Nico -妮可
Just override prepareForInterfaceBuilder() and add setAttributes().只需覆盖 prepareForInterfaceBuilder() 并添加 setAttributes()。
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setAttributes()
}
The tintColor
property will do the trick. tintColor
属性可以解决问题。 button.tintColor = UIColor.red
but to make sure to override the prepareForInterfaceBuilder()
但要确保覆盖
prepareForInterfaceBuilder()
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
button.tintColor = UIColor.red
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.