I am trying to create a customised UIButton. This customised button shows an unchecked box which will turn into a checked box, when the user presses the button. It will then return back to unchecked when user presses the checked box.
I have a runtime error. Debugger shows that it terminates because of an uncaught exception of type NSException.
Where does it goes wrong?
Code for the checked box
import UIKit
class CheckBox: UIButton {
//Images
let checkedImage = UIImage(named: "checked")
let unCheckedImage = UIImage(named: "unchecked")
//bool property
var isChecked:Bool = false {
didSet {
if isChecked == true{
self.setImage (checkedImage, forState: .Normal)
}
else {
self.setImage(unCheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender:UIButton) {
if(sender == self) {
if isChecked == true {
isChecked = false
} else {
isChecked = true
}
}
}
}
If you want to use selected attribute then you can do the following:
class CheckBox: UIButton {
//Images
let checkedImage = UIImage(named: "checked")
let unCheckedImage = UIImage(named: "unchecked")
//bool property
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked", forControlEvents: UIControlEvents.TouchUpInside)
self.setImage (checkedImage, forState: .Selected)
self.setImage(unCheckedImage, forState: .Normal)
}
func buttonClicked(sender:UIButton) {
if(sender == self) {
self.selected = !self.selected
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.