skip to Main Content

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


  1. 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
           
       }
    
       
       required init?(coder: NSCoder) {
           fatalError("init(coder:) has not been implemented")
       }
    
       func controlButton() -> Bool{
          if withDeleteButton{
             // show
             return true
         }else{
             // hide
             return false
         }
      }
     }
    

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

    And in your cell you can control and do what you want with it :

    cell.controlButton()
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search