Skip to content

Instantly share code, notes, and snippets.

@T-Pham
Last active May 26, 2020 11:50
Show Gist options
  • Save T-Pham/82e8f4fe9676cef4923aa05fff27f6cb to your computer and use it in GitHub Desktop.
Save T-Pham/82e8f4fe9676cef4923aa05fff27f6cb to your computer and use it in GitHub Desktop.
Custom UIControlState

The gist demonstrates how to add a custom UIControlState and set image for that state to a custom UIButton.

class MyButton: UIButton {
var error: Bool = false {
didSet {
setNeedsLayout()
}
}
override var state: UIControlState {
get {
return error ? UIControlState(rawValue: super.state.rawValue | UIControlState.Error.rawValue) : super.state
}
}
}
private extension UIControlState {
static let Error = UIControlState(rawValue: 1 << 16)
}
let myButton = MyButton()
myButton.setImage(UIImage(named: "ErrorCross"), forState: .Error)
myButton.setImage(UIImage(named: "ErrorCross"), forState: [.Error, .Highlighted])
myButton.setImage(UIImage(named: "ErrorCross"), forState: [.Error, .Selected])
myButton.setImage(UIImage(named: "ErrorCross"), forState: [.Error, .Selected, .Highlighted])
myButton.error = true
@sdpjswl
Copy link

sdpjswl commented May 26, 2020

and how would you define the 1 << 16 part if you wanted multiple custom states?

You could do this:

extension UIControl.State {
    static let customState = UIControl.State(rawValue: 1 << 16)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment