当状态为.disabled时,更改UIButton的颜色

时间:2018-03-27 15:57:10

标签: ios swift swift3 uibutton

我尝试在禁用时更改按钮图像颜色。提一下我的按钮也可以启用

事情是它总是灰色的。

    sendCodeBtn.isEnabled = false
    sendCodeBtn.setImage(#imageLiteral(resourceName: "validated_phone").withRenderingMode(.alwaysTemplate), for: .disabled)
    sendCodeBtn.tintColor = Theme.defaultColor()

5 个答案:

答案 0 :(得分:1)

您可以在情节提要中更改UIButton的所有属性。

更改图像中的状态:

enter image description here

然后设置颜色和图像等属性。

以编程方式

带图片:

sendCodeBtn.setBackgroundImage(UIImage(named: "yourImage.png"), for: .disabled) 

使用背景颜色:

sendCodeBtn.backgroundColor = UIColor .red

答案 1 :(得分:1)

Swift 4

如果你想以编程方式执行此操作(它看起来不漂亮,但可能):

func changeDisableButtonColor(button: UIButton, color: UIColor) {
    let rect = CGRect(x: 0.0, y: 0.0, width: myButton.frame.width, height: myButton.frame.height)
    UIGraphicsBeginImageContext(rect.size)

    let context = UIGraphicsGetCurrentContext()
    context?.setFillColor(color.cgColor)
    context?.fill(rect)

    let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    button.setBackgroundImage(image, for: .disabled)
}

用法:

changeDisableButtonColor(button: myButton, color: .red)

答案 2 :(得分:1)

@IBAction btn : UIButton!
if bin.state == .isSelected{
    btn.backgroundColor = UIColor.red
}

答案 3 :(得分:0)

swift 中,您可以通过多种方式执行此操作 -

@IBAction func onClickButtonStateChanged(sender: UIButton) {
    if(sender.isSelected){
        sender.backgroundColor = UIColor.red  //Highlighted
    }else{
        sender.backgroundColor = UIColor.grey . // disabled
    }
}

或者

override var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.red : UIColor.grey  // selected : disabled 
    }
}

另一种方式 -

   button.setBackgroundImage(UIImage(named: "button_image"), for: .normal)
   button.setBackgroundImage(UIImage(named: "button_image_selected"), for: .selected)
   button.setBackgroundImage(UIImage(named: "button_image_selected"), for: .disabled)
   button.setBackgroundImage(UIImage(named: "button_image_selected"), for: [.selected, .highlighted])

答案 4 :(得分:0)

要仅通过更改 isEnabled 属性值来更改按钮的颜色,可以添加观察者,如下所示:

btnConfirm.addObserver(self, forKeyPath: #keyPath(UIButton.isEnabled), options: .new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    btnConfirm.backgroundColor = btnConfirm.isEnabled ? .red : .lightGray
}

然后仅更改 isEnabled 属性以更改背景颜色。