如何以编程方式快速添加自定义UIButton

时间:2016-01-20 20:58:20

标签: ios swift class uibutton

我能够创建一个自定义复选框按钮类。但是,当我尝试将按钮放在我的视图中时,我无法获得图像。设置背景颜色只会返回该大小的正方形。这是我添加框的代码:

     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
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

awakeFromNib代码移至init()。 只有在从nib / xib文件初始化时才会调用awakeFromNib

这永远不会被召唤。您可以通过设置断点来测试它。

这应该是它的样子:

override init(frame: CGRect) {
    super.init(frame: frame)
    self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    self.isChecked = false
}

这样,self.isChecked被调用,图像被设置,你将看到的不仅仅是灰色框。