Skip to content

Instantly share code, notes, and snippets.

@acrookston
Last active February 15, 2018 18:14
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 acrookston/af50c921089b93d1d71e7a9349dc7af7 to your computer and use it in GitHub Desktop.
Save acrookston/af50c921089b93d1d71e7a9349dc7af7 to your computer and use it in GitHub Desktop.
A iOS UIButton subclass with support for background colors
//
// LICENSE: MIT
// Source: https://gist.github.com/acrookston/af50c921089b93d1d71e7a9349dc7af7
// Created by Andrew C on 4/16/17.
// Copyright © 2017 Andrew Crookston. All rights reserved.
//
import UIKit
extension UIControlState: Hashable {
public var hashValue: Int { return Int(rawValue) }
}
class BackgroundColorButton: UIButton {
func setBackgroundColors(_ options: [UIControlState: UIColor]) {
colors = options
updateBackgroundColor()
}
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
colors[state] = color
if state == .normal {
backgroundColor = color
}
}
// MARK: - overrides
override var isEnabled: Bool {
didSet { updateBackgroundColor() }
}
override var isHighlighted: Bool {
didSet { updateBackgroundColor() }
}
// MARK: - color switching
private lazy var colors: [UIControlState: UIColor] = [:]
private func setBackgroundToState(_ state: UIControlState) {
if let color = colors[state] {
backgroundColor = color
}
}
private func updateBackgroundColor() {
if !isEnabled {
setBackgroundToState(.disabled)
} else if isHighlighted {
setBackgroundToState(.highlighted)
} else {
setBackgroundToState(.normal)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment