[英]swift - customised button that terminate when pressed
I am trying to create a customised UIButton. 我正在尝试创建一个自定义的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. 调试器显示它因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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.