我有一个带有白色色调的关闭按钮的UIImageView
,但是如果背景图像为白色,则UIbutton不可见。我需要根据背景图像的颜色以编程方式更改UIButton
的颜色。
有什么方法可以根据放置在UIButton
中的图像更改UIImageView
的颜色吗?
答案 0 :(得分:0)
这是扩展名,用于根据其选择的状态,正常或突出显示来设置UIButton的背景色
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
self.clipsToBounds = true // add this to maintain corner radius
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
}
,您还可以将按钮的颜色设置为“喜欢”
loginButton.tintColor = .red