我创建了一个自定义类CircularButton
,在其中可以为图像设置自定义image
,backgroundColor
,tintColor
,并在图像的边缘设置inset
按钮。
除tintColor
之外,它都工作正常。我希望能够设置tintColor,但是如果我不提供它,它应该保留图像的原始tintColor(渲染为模板图像)。
open class CircularButton: UIButton {
public init(width: CGFloat, backgroundColor: UIColor? = nil, tintColor: UIColor? = nil, image: UIImage? = nil, contentMode: ContentMode? = nil, insets: UIEdgeInsets? = nil) {
super.init(frame: .zero)
self.backgroundColor = backgroundColor ?? .clear
self.tintColor = tintColor ?? // issue is here
self.imageEdgeInsets = insets ?? .zero
self.imageView?.contentMode = contentMode ?? .scaleAspectFit
setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal)
if width != 0 {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
heightAnchor.constraint(equalTo: widthAnchor).isActive = true
clipsToBounds = true
}
override open func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.width / 2
}
public required init?(coder aDecoder: NSCoder) {
fatalError()
}
}
这是我如何初始化它:
let likeButton = CircularButton(width: 45, backgroundColor: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5), tintColor: .white, image: UIImage(named: "heart"), insets: .init(top: 5, left: 5, bottom: 5, right: 5))
这是可行的,除了如果我不想提供tintColor,它会为按钮使用默认的蓝色tintColor并将我的图像呈现为蓝色。
这是我在自定义课程中尝试过的内容:
...
self.tintColor = tintColor ?? imageView?.tintColor
答案 0 :(得分:4)
您在此错误地将.alwaysTemplate
用作RenderingMode
,此属性用于更改图像的颜色,从而更改组件中色彩的原始颜色,应使用{{1} },如果您希望将图像的原始颜色保留在此组件中
要解决此问题,请在此行中使用.alwaysOriginal
代替.alwaysOriginal
.alwaysTemplate