Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created November 27, 2018 05:49
Show Gist options
  • Save wotjd/b7db2e315c48f408b982085f614bd676 to your computer and use it in GitHub Desktop.
Save wotjd/b7db2e315c48f408b982085f614bd676 to your computer and use it in GitHub Desktop.
A Simple ToggleButton with Color (subclassed UIButton)
import UIKit
class ToggleButton: UIButton {
@IBInspectable var toggledTintColor : UIColor?
private var prevTintColor : UIColor?
var isOn : Bool = false
convenience init() {
self.init(frame: CGRect.zero);
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initToggleButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initToggleButton()
}
func initToggleButton() {
self.addAction(for: .touchUpInside) {
if self.isOn {
self.tintColor = self.prevTintColor
} else {
self.prevTintColor = self.tintColor
self.tintColor = self.toggledTintColor
}
self.isOn = !self.isOn
}
}
deinit {
self.removeTarget(self, action: nil, for: .touchUpInside)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment