[英]How to add custom UIButton programmatically swift
I was able to create a custom checkbox button class. 我能够创建一个自定义复选框按钮类。 However, when I attempt to place the button in my view, I don't get an image.
但是,当我尝试将按钮放置在视图中时,没有得到图像。 Setting the background color simply returns a square of that size.
设置背景颜色仅会返回该大小的正方形。 Here is my code for adding the box:
这是我添加框的代码:
let box:CheckBox = CheckBox()
box.frame = CGRectMake(screenSize.width/2, screenSize.height/2, 200, 200)
self.view.addSubview(box)
I created the class as follows:
class CheckBox: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
//other stuff
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Images
let checkedImage = UIImage(named: "checked_checkbox")
let uncheckedImage = UIImage(named: "checkbox_unchecked_icon")
// 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
}
}
}
}
Move your awakeFromNib
code into your init()
. 将
awakeFromNib
代码移到init()
。 awakeFromNib
is only called when you're initialising from a nib/xib file. 仅当您从nib / xib文件进行初始化时,才调用
awakeFromNib
。
This never gets called. 这永远不会被调用。 You can test this by setting a breakpoint.
您可以通过设置断点来进行测试。
This is how it should look: 它应该是这样的:
override init(frame: CGRect) {
super.init(frame: frame)
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
This way, self.isChecked
gets called, an image is set, and you'll see more than a grey box. 这样,
self.isChecked
被调用,图像被设置,您将看到的不仅仅是一个灰色框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.