Skip to content

Instantly share code, notes, and snippets.

@shishirthedev
Created January 8, 2019 20:02
Show Gist options
  • Save shishirthedev/9b2bf0f09f9a0c20392b06b4abcbfc35 to your computer and use it in GitHub Desktop.
Save shishirthedev/9b2bf0f09f9a0c20392b06b4abcbfc35 to your computer and use it in GitHub Desktop.
import UIKit
@IBDesignable class CheckedButton: UIButton {
@IBInspectable var checked: Bool = false {
didSet {
updateImage()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
}
internal func setup() {
self.addTarget(self, action: #selector(tapped), for: .touchUpInside)
}
private func updateImage() {
let bundle = Bundle(for: CheckedButton.self)
let image = checked ? UIImage(named: "checked_box", in: bundle, compatibleWith:nil) : UIImage(named: "unchecked_box", in: bundle, compatibleWith:nil)
self.setBackgroundImage(image, for: .normal)
}
/// Called each time the button is tapped, and toggles the checked property
@objc private func tapped() {
checked = !checked
print("New value: \(checked)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment