Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@T-Pham
Last active May 26, 2020 11:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@pavankataria
Copy link

pavankataria commented Nov 29, 2017

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

@bidluo
Copy link

bidluo commented Dec 18, 2017

@pavankataria 1 << 16 until 1 << 23 are reserved for custom states, so you can have 9 different states

@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