我有这个UICollectionViewCell子类,我正在尝试在初始化时将值传递给单元格。
class AddItemCell: UICollectionViewCell {
var addItemButton = UIButton()
var collectionElement : PFObject?
override init(frame: CGRect) {
super.init(frame: frame)
addItemButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
addItemButton.frame = CGRectMake(0, 0, 170, 300)
addItemButton.backgroundColor = UIColor.redColor()
addItemButton.addTarget(self, action: "addItemToCollectionElement:", forControlEvents: UIControlEvents.TouchUpInside)
addItemButton.setTitle("New Item", forState: UIControlState.Normal)
addItemButton.titleLabel!.font = UIFont(name: "Cochin-BoldItalic", size: 20)
self.addSubview(addItemButton)
}
init (frame: CGRect, passedCollectionElement : PFObject){
self.collectionElement = passedCollectionElement
super.init(frame: frame)
}
func addItemToCollectionElement (sender : UIButton!) {
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
显然,被调用的方法是被覆盖的方法。有没有办法调用第二种/任何其他方式传递变量值?
答案 0 :(得分:2)
如果你想用一些额外的参数初始化你的对象并使得被覆盖的init也被调用,你需要使用便利初始化器,如下所示:
convenience init (frame: CGRect, passedCollectionElement : PFObject){
self.init(frame: frame)
self.collectionElement = passedCollectionElement
}
这种方式通过调用let cell = AddItemCell(frame:someFrame, passedCollectionElement : someElement)
将通过调用方便和指定的初始值设定项来初始化您的对象。您可以详细了解初始化here