Skip to content

Instantly share code, notes, and snippets.

@robinkanatzar
Created October 16, 2019 08:53
Show Gist options
  • Save robinkanatzar/e35d42f80c4eb4f6132f22288ba3d1a6 to your computer and use it in GitHub Desktop.
Save robinkanatzar/e35d42f80c4eb4f6132f22288ba3d1a6 to your computer and use it in GitHub Desktop.
Custom CheckBox in Swift
import UIKit
class MyCheckBox: UIButton {
let checkedImage = UIImage(named: "checkbox_checked")
let uncheckedImage = UIImage(named: "checkbox_not_checked")
var isChecked: Bool = false {
didSet {
if isChecked == true {
self.setImage(checkedImage, for: .normal)
} else {
self.setImage(uncheckedImage, for: .normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isChecked = false
}
@objc func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
@robinkanatzar
Copy link
Author

In the Storyboard:

  • Add a new UIButton element
  • Set the UIButton type to Custom
  • Delete the Default Title
  • Set the Custom Class to MyCheckBox
  • Set constraints such as height and width

gist_1
gist_2

XCode Version: 11.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment