简体   繁体   中英

Is it possible to define tint color for a disabled UIButton?

For some reason, I want to define my own tint color, when an UIButton is disabled.

I thought it is able to achieve so based on

https://stackoverflow.com/a/45835079/72437

import UIKit

class UIButtonEX: UIButton {
    override var isEnabled: Bool {
        didSet{
            if self.isEnabled {
                self.tintColor = UIColor.red
            }
            else{
                self.tintColor = UIColor.red
            }
        }
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButtonEX!
    
    @IBOutlet weak var disabledButton: UIButtonEX!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        button.isEnabled = true
        disabledButton.isEnabled = false
        
        //button.tintColor = .red
        //disabledButton.tintColor = .red
    }

}

The right button is disabled UIButton . I wish it would stay in red even it is disabled.

在此处输入图像描述

However, it is still painted as default system light grey.

May I know, what steps I have missed out? Is it possible to define tint color for a disabled UIButton?

Thanks.

You may have to try something like this, and this works when you are using the system named images.

class UIButtonEX: UIButton {
    override func tintColorDidChange() {
        if tintAdjustmentMode == .dimmed {
            // modify subviews to look disabled
            // In your case tou have to heep as it is
            tintAdjustmentMode = .normal
        } else {
            // modify subviews to look enabled
        }
    }
}

Try this:

class UIButtonEX: UIButton {
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        adjustsImageWhenDisabled = false
        setTitleColor(tintColor, for: .disabled)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM