Skip to content

Instantly share code, notes, and snippets.

@hishma
Created April 1, 2020 21:32
Show Gist options
  • Save hishma/c5fc83f6ffe42cc4b57d0cd104abbc3b to your computer and use it in GitHub Desktop.
Save hishma/c5fc83f6ffe42cc4b57d0cd104abbc3b to your computer and use it in GitHub Desktop.
Hand rolled button, Heasley style.
import UIKit
class Button: UIControl {
var labelText: String? {
set {
label.text = newValue
}
get {
label.text
}
}
convenience init(label text: String? = nil) {
self.init(frame: .zero)
self.labelText = text
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setUp()
}
private let label: UILabel = UILabel()
private func setUp() {
clipsToBounds = true
layer.cornerRadius = 9.0
layer.cornerCurve = .continuous
layer.borderWidth = 1.0
label.text = "Button"
label.textAlignment = .center
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.frame = bounds
addSubview(label)
}
// MARK: UIControl
override var isEnabled: Bool {
didSet {
setNeedsLayout()
layoutIfNeeded()
}
}
override var isSelected: Bool {
didSet {
setNeedsLayout()
layoutIfNeeded()
}
}
override var isHighlighted: Bool {
didSet {
setNeedsLayout()
layoutIfNeeded()
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setNeedsLayout()
layoutIfNeeded()
}
override func layoutSubviews() {
super.layoutSubviews()
layer.borderColor = UIColor.label.cgColor
label.textColor = isSelected ? .systemBackground : .label
backgroundColor = isSelected ? .label : (isHighlighted ? .systemGray : .clear)
alpha = isEnabled ? 1.0 : 0.5
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment