Skip to content

Instantly share code, notes, and snippets.

@hanawat
Created April 16, 2019 05:53
Show Gist options
  • Save hanawat/fc7f710dbf92d529704960879cc5b0b6 to your computer and use it in GitHub Desktop.
Save hanawat/fc7f710dbf92d529704960879cc5b0b6 to your computer and use it in GitHub Desktop.
Selectable Color Button
import UIKit
/// The Selectable Color Button
class ColorButton: UIButton {
/// Highlighted Background Color
@IBInspectable var highlightedColor: UIColor?
/// Selected Background Color
@IBInspectable var selectedColor: UIColor?
/// Disabled Background Color
@IBInspectable var disabledColor: UIColor?
/// Original Background Color
private var originalColor: UIColor?
/// Whether changing color by user or not.
private var isChanging = true
override var backgroundColor: UIColor? {
didSet {
guard isChanging else { return }
originalColor = backgroundColor
}
}
override var isHighlighted: Bool {
didSet { changeColor(highlightedColor, changing: isHighlighted) }
}
override var isSelected: Bool {
didSet { changeColor(selectedColor, changing: isSelected) }
}
override var isEnabled: Bool {
didSet { changeColor(disabledColor, changing: !isEnabled) }
}
/// Changing Background Color
///
/// - Parameters:
/// - color: Color
/// - changing: Whether changing or not.
private func changeColor(_ color: UIColor?, changing: Bool) {
guard let color = color else { return }
isChanging = false
UIView.animate(withDuration: 0.25, animations: { [weak self] in
self?.backgroundColor = changing ? color : self?.originalColor
})
isChanging = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment