我使用以下代码创建了一个自定义按钮类,该类具有方法style(_:image:)
:
extenstion CustomButton {
func style(_ buttonStyle: ButtonStyle, image: UIImage? = nil) {
self.textStyle = buttonStyle.textStyle
setTitle(self.titleLabel?.text, for: .normal)
switch buttonStyle.backgroundStyle {
case .solid:
self.backgroundColor = buttonStyle.backgroundColor
case .border:
self.layer.borderWidth = 1.0
self.layer.borderColor = textStyle!.color.cgColor
case .none:
self.layer.borderWidth = 0.0
}
self.layer.cornerRadius = 3.0
guard let image = image else {
return
}
setImage(image, for: .normal)
imageEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 0)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView!.bounds.width, bottom: 0, right: 0)
imageView!.tintColor = textStyle?.color
}
}
我已经注意到,在加载视图时,有片刻的时间看起来一切都很好(即按钮图像的颜色应该是应该的。然后,该按钮会进行动画处理,就像被单击一样,并且色泽会恢复为默认为蓝色。这似乎是在以下代码中使用setAttributedTitle(_:for:)
的直接结果:
class CustomButton: UIButton {
var textStyle: TextStyle?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func setTitle(_ title: String?, for state: UIControl.State) {
guard let style = textStyle,
let text = title else {
super.setTitle(title, for: state)
return
}
setAttributedTitle(style.attributedString(string: text), for: state)
}
}
如果我注释掉setAttributedTitle(_:for:)
方法,则图像具有正确的色彩,但是现在我错过了应用自定义文本样式的机会。
有什么想法吗?我感谢所有帮助!