[英]iOS 9 Swift UIButton CheckBox subclass not showing image
I subclassed UIButton
to make a CheckBox
... The code below seems to work on storyboard (according to online tutorials) but when i try to add it by code it doesn't work... 我将UIButton
子类UIButton
一个CheckBox
...下面的代码似乎可以在情节提要上使用(根据在线教程),但是当我尝试通过代码添加它时,它不起作用...
class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "Checked.png")! as UIImage
let uncheckedImage = UIImage(named: "Unchecked.png")! as UIImage
// 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: #selector(CheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
Here is the code I use on my ViewController
to add the CheckBox: 这是我在ViewController
用来添加CheckBox的代码:
let checkbox = CheckBox(frame: CGRect(x: 5, y: 5, width: 40, height: 40))
print(checkbox.isChecked)
view.addSubview(checkbox)
The problem is that the CheckBox
is not being displayed. 问题是没有显示CheckBox
。 If I give it a background, under the frame initialization then I can see the square but if nothing happens when I click it.. Even after adding a print message in the buttonClicked
method. 如果为它提供背景,则在框架初始化下可以看到该正方形,但是单击该正方形时什么也没有发生。即使在buttonClicked
方法中添加了打印消息后,也可以看到正方形。
I added print statements in the awakeFromNib method and it was never called... 我在awakeFromNib方法中添加了打印语句,但从未调用过它。
已修复..如果没有Storyboard,AwakeFromNib显然不会被调用,因此我必须实现一个便捷的初始化程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.