struct ColorControl {
let color: UIColor
let controlState: UIControlState
}
extension UIButton {
var tt: ColorControl? {
get {
return nil
}
set(cc) {
if let colorControl = cc {
setTitleColor(colorControl.color, for: colorControl.controlState)
}
}
}
}
// Usage
let button = UIButton()
button.tt = ColorControl(color: .red, controlState: .normal)
// Usage
let button = UIButton()
button.setTitleColor(UIColor.red, for: .normal)
// UIControlStateの複数指定に未対応
extension UIButton {
enum ColorControl {
case normal(UIColor)
case highlighted(UIColor)
case disabled(UIColor)
case selected(UIColor)
@available(iOS 9.0, *)
case focused(UIColor)
case application(UIColor)
case reserved(UIColor)
func getColor() -> UIColor? {
switch self {
case ColorControl.normal(let color):
return color
case ColorControl.highlighted(let color):
return color
case ColorControl.disabled(let color):
return color
case ColorControl.selected(let color):
return color
case ColorControl.focused(let color):
return color
case ColorControl.application(let color):
return color
case ColorControl.reserved(let color):
return color
}
}
func getControl() -> UIControlState {
switch self {
case ColorControl.normal(_):
return UIControlState.normal
case ColorControl.highlighted(_):
return UIControlState.highlighted
case ColorControl.disabled(_):
return UIControlState.disabled
case ColorControl.selected(_):
return UIControlState.selected
case ColorControl.focused(_):
return UIControlState.focused
case ColorControl.application(_):
return UIControlState.application
case ColorControl.reserved(_):
return UIControlState.reserved
}
}
}
func titleColor(_ colorControl: ColorControl) {
setTitleColor(colorControl.getColor(), for: colorControl.getControl())
}
}
// Usage
let button = UIButton()
button.titleColor(.normal(UIColor.red))