根据状态更改UIButton中ImageView的色调颜色

时间:2019-07-17 04:22:59

标签: ios swift xcode uibutton uiimageview

我在情节提要中有一个UIButton,它只显示没有文字的图像。它的类型是系统。轻按按钮时,需要更改图像的色调颜色。我该如何使用UIButton's状态配置?

我尝试在代码中setImage表示不同的状态,如下所示,但无法使其正常工作。谢谢

setImage(UIImage(named: "test")?.applying(tintColor: .red), for: .highlighted)
setImage(UIImage(named: "test")?.applying(tintColor: .blue), for: .normal)

2 个答案:

答案 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

有关详细信息,请参考图片this image will shows the attributed inspector render option

答案 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
    }
}
相关问题