Skip to content

Instantly share code, notes, and snippets.

@moderateepheezy
Created September 17, 2020 10:13
Show Gist options
  • Save moderateepheezy/33aea3826db41de71ebb59a9ab98bed0 to your computer and use it in GitHub Desktop.
Save moderateepheezy/33aea3826db41de71ebb59a9ab98bed0 to your computer and use it in GitHub Desktop.
import UIKit
final class ColorSelectionControl: UIControl {
private var buttons = [UIButton]()
private let colors: [UIColor]
lazy var currentSelectedColor: UIColor = colors[0]
init(colors: [UIColor]) {
self.colors = colors
super.init(frame: .zero)
updateView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func customize(_ button: UIButton, index: Int, isSelected: Bool = false) {
button.backgroundColor = colors[index]
button.layer.borderWidth = isSelected ? 2 : 0
button.layer.borderColor = isSelected ? UIColor.deepBlue.cgColor : UIColor.clear.cgColor
}
private func updateView() {
for color in colors {
let button = UIButton.init(type: .system)
button.backgroundColor = color
button.layer.cornerRadius = 14
button.addTarget(self, action: #selector(buttonTapped(button:)), for: .touchUpInside)
button.constrain(size: .init(width: 28, height: 28))
buttons.append(button)
}
customize(buttons[0], index: 0, isSelected: true)
// Create a StackView
let stackView = UIStackView.init(arrangedSubviews: buttons).layoutable()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 16
addSubview(stackView)
stackView.constraintCenter(to: self, axis: [.horizontal, .vertical])
}
@objc private func buttonTapped(button: UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
customize(btn, index: buttonIndex)
if btn == button {
currentSelectedColor = colors[buttonIndex]
customize(btn, index: buttonIndex, isSelected: true)
}
}
sendActions(for: .valueChanged)
}
func updateSelectorControl(index: Int) {
for btn in buttons {
customize(btn, index: index)
}
currentSelectedColor = colors[index]
customize(buttons[index], index: index, isSelected: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment