[英]Swift Setting subclass UIButton ButtonType
I have a simple subclass of UIButton
我有一个简单的UIButton
子类
class IconButton: UIButton {
init(type: FontAwesomeStyle, icon: FontAwesome, color: UIColor = .black, size: CGFloat = 20) {
super.init(frame: CGRect.zero)
let iconAsText = String.fontAwesomeIcon(name: icon)
let iconText = NSMutableAttributedString(string: iconAsText, attributes: [
NSAttributedString.Key.font: UIFont.fontAwesome(ofSize: size, style: type)
])
setAttributedTitle(iconText, for: .normal)
setTitleColor(color, for: .normal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The problem I am having is that I would like the button to have the behavior that system buttons have.我遇到的问题是我希望按钮具有系统按钮具有的行为。 Specifically when you press and hold the button, it changes color.特别是当您按住按钮时,它会改变颜色。
let button = UIButton(type: .system)
Since buttonType
is a get only property of UIButton and UIButton.init(type: UIButton.ButtonType)
is a convenience initailizer, I am not sure how to implement this a subclass.由于buttonType
是 UIButton 的一个 get only 属性,而UIButton.init(type: UIButton.ButtonType)
是一个方便的初始化程序,我不确定如何实现它的子类。
Still not sure if its possible to replicate the .system
button type in a subclass, but the solution for getting the behavior I wanted was the following:仍然不确定是否可以在子类中复制.system
按钮类型,但获得我想要的行为的解决方案如下:
class IconButton: UIButton {
override var isHighlighted: Bool {
willSet(newVal) {
if newVal != isHighlighted {
// newVal is true when the button is being held down
}
}
}
// Rest of class...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.