Reputation: 2408
I've created the following custom UIButton:
import Foundation
import UIKit
class WhiteGhostYouButton: UIButton {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
self.titleLabel?.textColor = UIColor.white
self.borderWidth = 2
self.borderColor = UIColor.white
self.cornerRadius = 23
}
}
This works great!
Now I also want to implement a custom Disabled state for this button.
How do I go about this?
This doesn't seem to work:
import Foundation
import UIKit
class GhostYouButton: UIButton {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if (self.isEnabled == false) {
self.backgroundColor = UIColor.clear
self.titleLabel?.textColor = Constant.disabledGrayColor
self.tintColor = Constant.disabledGrayColor
self.borderColor = Constant.disabledGrayColor
self.borderWidth = 2
self.cornerRadius = 20
} else {
self.backgroundColor = UIColor.clear
self.titleLabel?.textColor = Constant.mainGreenColor
self.tintColor = Constant.mainGreenColor
self.borderColor = Constant.mainGreenColor
self.borderWidth = 2
self.cornerRadius = 20
}
}
}
The viewDidLoad that disables my button:
override func viewDidLoad() {
self.nextButton.isEnabled = false
}
Upvotes: 1
Views: 2219
Reputation: 21
For customizing the WhiteGhostYouButton as per the states like disabled state. You need to add drawRect method inside the custom class as per below code snippet.
class WhiteGhostYouButton: UIButton {
override func draw(_ rect: CGRect) {
super.draw(rect)
if self.isEnabled = false {
//Customize UI here
} esle {
}
}
}
On any event like button press, re rendering of view can be forced as per below code snippet
@IBAction func button_Pressed(sender: AnyObject) {
sender.setNeedsDisplay()
}
Upvotes: 0
Reputation: 148
I think you can try to implenment the didSet
of isEnable
:
override var isEnabled: Bool {
didSet {
if (self.isEnabled == false) {
self.backgroundColor = UIColor.clear
self.titleLabel?.textColor = Constant.disabledGrayColor
self.tintColor = Constant.disabledGrayColor
self.borderColor = Constant.disabledGrayColor
self.borderWidth = 2
self.cornerRadius = 20
} else {
self.backgroundColor = UIColor.clear
self.titleLabel?.textColor = Constant.mainGreenColor
self.tintColor = Constant.mainGreenColor
self.borderColor = Constant.mainGreenColor
self.borderWidth = 2
self.cornerRadius = 20
}
}
hope this can help you :)
Upvotes: 4