|
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() |
|
} |
|
} |
|
} |