Home > Mobile >  Convenience Init For UICollectionViewCell
Convenience Init For UICollectionViewCell

Time:12-09

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

Any help is greatly appreciated.

CodePudding user response:

I think, you should use this way.

enter image description here

CodePudding user response:

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 programatically override 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:

class MediaSelectionCell: UICollectionViewCell {

var withDeleteButton = false
   
   override init(frame: CGRect) {
       super.init(frame: frame)
       // maybe adding constraint your bla bla
       
       if withDeleteButton == true{
           //showbutton
       }else{
           //hide button
       }
   }
   
   required init?(coder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }

}

One for showing button :

class MediaSelectionShowButton : MediaSelectionCell{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.withDeleteButton = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
  • Related