选定UIButton上的奇怪tintColor

时间:2016-12-23 16:27:50

标签: ios swift uibutton

如果选择了我的UI按钮:

     let image = UIImage(named: "photo-camera")?.imageWithRenderingMode(.AlwaysTemplate)
     btnPhoto.setImage(image, forState: .Normal)
     btnPhoto.tintColor = UIColor.orange()

如果我的UI按钮已选中:

    let image = UIImage(named: "photo-camera")?.imageWithRenderingMode(.AlwaysTemplate)
    btnPhoto.setImage(image, forState: .Normal)
    btnPhoto.tintColor = UIColor.grayColor()

现在,我的问题是:当未选择UIButton时,一切都显示正常: enter image description here 相反,当选择UIButton时,结果为:enter image description here

色调颜色不会改变图像而是改变背景。我不明白为什么。

3 个答案:

答案 0 :(得分:0)

只需为所选状态设置图像,并将色调颜色设置为清除。

答案 1 :(得分:0)

使用自定义

类型的btnPhoto
let btnPhoto = UIButton(type: .Custom)
let image = UIImage(named: "image_name")?.imageWithRenderingMode(.AlwaysTemplate)
btnPhoto.setImage(image, forState: .Normal)
btnPhoto.tintColor = UIColor.grayColor()

btnPhoto.addTarget(self, action: “btntSelected:", forControlEvents: .TouchUpInside)

func btnSelected(sender : UIButton)
{
var btn:UIButton = sender
btn.tintColor = UIColor.orange()
}

答案 2 :(得分:0)

您必须设置setBackgroundImage,而不是setImage。

class CustomTintButton: UIButton {

override public var isSelected: Bool{
    didSet {
        if self.isSelected {
            self.tintColor = .orange
        }
        else{
            self.tintColor = .gray
        }

      }
}