UIButton tintColor for disabled and enabled state?
You can attempt to replicate the setX(_ x: X, forState: State)
API like this:
private class TintColorButton: UIButton {
private var tintDict: [State.RawValue: UIColor] = [:]
private var store: Set<AnyCancellable> = []
override init(frame: CGRect) {
super.init(frame: frame)
publisher(for: \.isHighlighted).sink { [weak self] _ in self?.applyTintColor() }.store(in: &store)
publisher(for: \.isEnabled).sink { [weak self] _ in self?.applyTintColor() }.store(in: &store)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setTintColor(_ color: UIColor?, forState state: State) {
tintDict[state.rawValue] = color
applyTintColor()
}
private func applyTintColor() {
tintColor = tintDict[state.rawValue] ?? tintDict[State.normal.rawValue]
}
}
You could override the isEnabled property to achieve that. The tintColor will be automatically changed according to the button's isEnabled status:
class ButtonsPostMenu:UIButton {
//......
override var isEnabled: Bool {
didSet{
if self.isEnabled {
self.tintColor = UIColor.white
}
else{
self.tintColor = UIColor.gray
}
}
}
//......
}
This is your class: Add changeStateOfButton
custom method for manage tint color of UIButton
class ButtonsPostMenu: UIButton
{
override func awakeFromNib()
{
titleLabel?.font = UIFont(name: Font_AvenirNext_Medium, size: 14)
tintColor = UIColor.white
}
func changeStateOfButton() {
if self.isEnabled {
self.tintColor = UIColor.red // Set your color when button is enabled
}
else {
self.tintColor = UIColor.yellow // Set your color when button is disabled
}
}
}
And just call above method like when you want to set color based on enable/disable UIButton
.