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

Posted

技术标签:

【中文标题】根据状态更改 UIButton 中 ImageView 的 tint 颜色【英文标题】:Change ImageView's tint color in UIButton based on state 【发布时间】:2019-07-17 04:22:59 【问题描述】:

我在情节提要中有一个UIButton,它只显示图像而不显示文本。它的类型是系统。点击按钮时需要更改图像的色调颜色。我如何使用UIButton's 状态配置来做到这一点?

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

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

【问题讨论】:

【参考方案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
    

【讨论】:

【参考方案2】:
 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

详情请看图片

【讨论】:

这也有效,但我更愿意在代码中做同样的事情。谢谢

以上是关于根据状态更改 UIButton 中 ImageView 的 tint 颜色的主要内容,如果未能解决你的问题,请参考以下文章

更改 UIToolBar 中所有按钮的 UIButton 状态

使用通知中心在 Realm Swift 3 中保存 UIButton 更改状态

选择时避免 UIButton 反转颜色

针对不同状态更改 UIButton 的渐变

根据状态设置自定义 UIButton 样式

在 UITableView 顶部按下时,UIButton 不会更改其状态