I have a custom class
that inherits from UIButton
. The thing that I want to accomplish is setting the tintColor
property based on the button's enabled state (i.e enabled or disabled).
Is there any way to achieve that?
This is my class:
class ButtonsPostMenu: UIButton
{
override func awakeFromNib()
{
titleLabel?.font = UIFont(name: Font_AvenirNext_Medium, size: 14)
tintColor = UIColor.white
}
}
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
.
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]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With