Skip to content

Instantly share code, notes, and snippets.

@T-Pham T-Pham/MyButton.swift
Last active Mar 21, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Nov 29, 2017

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

@bidluo

This comment has been minimized.

Copy link

commented Dec 18, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.