Skip to content

Instantly share code, notes, and snippets.

@pavankataria
Created November 29, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavankataria/3d69f9599e86f04dd6f55ce212e0bebf to your computer and use it in GitHub Desktop.
Save pavankataria/3d69f9599e86f04dd6f55ce212e0bebf to your computer and use it in GitHub Desktop.
A UIButton subclass that renders a sort button.
fileprivate extension UIControlState {
static let unspecified = UIControlState(rawValue: 1 << 16)
static let ascending = UIControlState(rawValue: 1 << 17)
static let descending = UIControlState(rawValue: 1 << 18)
}
class SortButton: UIButton {
private var customState: UIControlState = .unspecified {
didSet {
setNeedsLayout()
}
}
override var state: UIControlState {
return customState
}
convenience init(){
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup(){
self.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
self.setImage(UIImage(named: "column-sort-unspecified"), for: .unspecified)
self.setImage(UIImage(named: "column-sort-ascending"), for: .ascending)
self.setImage(UIImage(named: "column-sort-descending"), for: .descending)
//Safety feature. Find out how to make this comply, 16 bit vs 8 bit issue
//assert(UIControlState.unspecified & UIControlState.application, "The custom state is not within UIControlStateApplication")
//assert(UIControlState.ascending & UIControlState.application, "The custom state is not within UIControlStateApplication")
//assert(UIControlState.descending & UIControlState.application, "The custom state is not within UIControlStateApplication")
setUnspecified()
}
override func setTitle(_ title: String?, for state: UIControlState) {
print("Setting the title on this SortButton I've created is not supported yet, mainly because I haven't figured out a nice way to cater for the layout")
}
@objc func buttonTapped(){
self.toggle()
}
func setUnspecified(){
self.customState = UIControlState.unspecified
}
func setAscending(){
self.customState = .ascending
}
func setDescending(){
self.customState = .descending
}
func toggle(){
//Escape early if the state is unspecified and toggle to ascending.
guard self.customState != .unspecified else {
self.setAscending()
return
}
if self.customState == .ascending {
self.setDescending()
}
else {
self.setAscending()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment