I have a custom UICollectionViewCell
that I use in two places throughout my project.
Both UICollectionViewCell
‘s are the same apart from showing a UIButton
. To reduce duplication of code I want to use the cell in both places but initialize one with a Boolean that determines if the button is shown or not.
I believe I need a convenience initializer to do this, however, I am getting the error;
‘self’ used before ‘self.init’ call or assignment to ‘self’
Code:
class MediaSelectionCell: UICollectionViewCell {
var withDeleteButton = false
convenience init(showsDeleteButton: Bool) {
self.init(showsDeleteButton: withDeleteButton)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
How can I resolve this?
2
Answers
Your collectionview cell initialization doesn’t have a methods called
self.init(showsDeleteButton: withDeleteButton)
that why you are getting an error message.As said in the comment, cells are reuseable. If you register cell with storyboard ,
required init?(coder: NSCoder)
initialization methods called , If you register cell programaticallyoverride init(frame: CGRect)
is called.So I mean, If you use
dequeueReusableCell
you can not change the initialization method by hands.I prefer to create a two classes to do what you want:
One for not showing button:
One for showing button :
And in your cell you can control and do what you want with it :
You can’t use a convenience initializer for table view or collection view cells because the table view/collection view creates them by calling the designated initializer.
You have to add a property to your custom class and set it up to honor that property.