iphone - 在 Swift 中以编程方式将类添加到 UIbutton

标签 iphone swift uibutton

我是 Swift 新手,对如何以编程方式向按钮添加自定义类感到困惑。我创建了一个自定义类,并可以使用 Storyboard添加它。它工作得很好,但是如何以编程方式完成呢?

enter image description here

我可以使用 CheckBox 类代替 UIButton 还是仍然需要使用 UIButton 并添加该类?

类(class)

class CheckBox: UIButton {

//images
let checkedImage = UIImage(named: "checked_checkbox") //as UIImage!
let uncheckedImage = UIImage(named: "unchecked_checkbox") //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: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    self.isChecked = false
}


func buttonClicked(sender:UIButton) {
    if(sender == self){
        if isChecked == true {
            println("setting to false")
            isChecked = false
        }else{
             println("setting to true")
            isChecked = true
        }
    }
}
}

将类添加到 View Controller

override func viewDidLoad() {
    super.viewDidLoad()

    let checkBox = CheckBox()

    checkBox.backgroundColor = UIColor.blueColor()
    self.view.addSubview(checkBox)

    checkBox.setTranslatesAutoresizingMaskIntoConstraints(false)


    self.view.addConstraint(NSLayoutConstraint(item: checkBox, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 50))
    self.view.addConstraint(NSLayoutConstraint(item: checkBox, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 50))


}

最佳答案

the checkbox does not appear

这可能是因为您忘记给您的复选框指定大小吗?

另外,我注意到你有这些图片:

let checkedImage = UIImage(named: "checked_checkbox") //as UIImage!
let uncheckedImage = UIImage(named: "unchecked_checkbox") //as UIImage!

但是您是否忘记将这些图像中的任何一个放入按钮?我没有看到任何执行此操作的代码。

If I call checkbox.isCheck = true or false the checkbox appears but does not change if clicked

这可能是因为您忘记为其控制事件提供任何目标操作吗?以前您有以下代码:

override func awakeFromNib() {
    self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    self.isChecked = false
}

但现在没有 awakeFromNib 调用 - 此按钮不会从 Nib 唤醒。 Storyboard就是 Nib 。该按钮现在来自代码。

如果你解决这个问题,以便调用该代码,那么将设​​置 isChecked 并且图像将会出现,不是吗?

关于iphone - 在 Swift 中以编程方式将类添加到 UIbutton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226476/

相关文章:

ios - 如何让 UIButton 同时做两件事?

ios - 自定义 UIButton 不起作用

iphone - 我怎样才能只舍入 UIView 的底角?

objective-c - Apple最新(2015) 'link to app store'指令导致不必要的Safari行为

iphone - 命令/usr/bin/codesign 失败,退出代码为 1

ios - 设备静音时 AVAudioPlayer 没有声音

ios - 何时使用 respondsToSelector 与 objc_getClass

iphone - UIPanGestureRecognizer - View 在拖动时消失

ios - 从 iOS 应用程序在 youtube 上上传视频?

swift - 来自单个 UIButton 的两个 "Different"按钮?