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.

Revisions

  1. hishma revised this gist Apr 1, 2020. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions Button.swift
    Original file line number Diff line number Diff line change
    @@ -12,6 +12,7 @@ class Button: UIControl {

    convenience init(label text: String? = nil) {
    self.init(frame: .zero)
    self.labelText = text
    }

    required init?(coder: NSCoder) {
  2. hishma created this gist Apr 1, 2020.
    79 changes: 79 additions & 0 deletions Button.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,79 @@
    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)
    }

    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()
    }
    }