我在情节提要中有一个UIButton
,它只显示没有文字的图像。它的类型是系统。轻按按钮时,需要更改图像的色调颜色。我该如何使用UIButton's
状态配置?
我尝试在代码中setImage
表示不同的状态,如下所示,但无法使其正常工作。谢谢
setImage(UIImage(named: "test")?.applying(tintColor: .red), for: .highlighted)
setImage(UIImage(named: "test")?.applying(tintColor: .blue), for: .normal)
答案 0 :(得分:1)
Follow the below steps plus your already done work:
1) Go to Images.xcassets and select your image i.e test
2) Click on attribute inspector on the right hand side of xcode
3) Change Render as option from "Default" to "Template Image"
4) Run again and test
答案 1 :(得分:1)
检查以下代码:-
@IBAction func onClickButton(_ sender: UIButton) {
sender.imageView.image = sender.imageView.image?.withRenderingMode(.alwaysTemplate)
if sender.isSelected || sender.isHighlighted{
sender.imageView.tintColor = .red
}else{
sender.imageView.tintColor = .blue
}
}