源码

如何为UIButton保留图像tintColor?

我创建了一个自定义类CircularButton,我可以在其中为图像设置自定义图像,backgroundColor,tintColor,并插入按钮的边缘。
它的工作正常,除了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))

self.tintColor = tintColor ?? imageView?.tintColor

修复方法:.alwaysOriginal而不是.alwaysTemplate在这一行

setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal)

(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/ruheweiuibuttonbaoliutuxiangtintcolor.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:8 月 21, 2019 at 01:18 上午

热评文章