【问题标题】:Template UIImage changes color [duplicate]模板 UIImage 更改颜色 [重复]
【发布时间】:2017-12-15 13:22:55
【问题描述】:

我编写了这段代码来创建一个带有 UIImage 的按钮。

func createDrawerBarButton(image : String) {

    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: image)?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)

    button.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
    button.tintColor = UIColor(red: 208/255, green: 33/255, blue: 33/255, alpha: 1.0)
    button.addTarget(self, action: #selector(self.drawerClicked(_:)), for: UIControlEvents.touchUpInside)

    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.leftBarButtonItem = barButton

}

当我单击按钮时,它会调用一个显示警报的方法。方法是这样的:

func drawerClicked(_ sender: Any) {
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    let wifiAction = UIAlertAction(title: "Wi-Fi", style: .default) { (UIAlertAction) in
        let url = URL(string: "App-Prefs:root=WIFI")
        UIApplication.shared.openURL(url!)
    }

    let alert = UIAlertController(title: "Wi-Fi)", message: "Please, connect your WI-FI", preferredStyle: .alert)

    alert.addAction(cancelAction)
    alert.addAction(wifiAction)
    self.present(alert, animated: true, completion: nil)
}

效果很好,但是当对话框出现时,我的 UIImage 会改变颜色。红色变成灰色。关闭对话框后, UIImage 恢复为红色。即使出现警报,我也希望该图像保持红色,仅比屏幕的其余部分稍暗。我该怎么做?

【问题讨论】:

    标签: ios cocoa-touch uiimage


    【解决方案1】:

    我认为问题是当您点击按钮时,它会突出显示或被选中,但是您仅将图像设置为正常状态,因此您需要更改此设置

    button.setImage(UIImage(named: image)?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
    

    有了这个

    button.setImage(UIImage(named: image)?.withRenderingMode(.alwaysTemplate), for: [.normal, .selected, .highlighted ])
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 2018-08-20
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多