How to Initialize CollectionView Cell?

Hi Apple Developer Community,
Swift noob here.
I was subclassing UICollectionViewCell when I realized I needed to initialize it in some way.
So far, I have found init(frame: CGRect), init?(coder aDecoder:NSCoder), and awakeFromNib( ).
Which is the preferred way to initialize a custom UICollectionViewCell (or a custom calss in general)?
Thanks in advance! 🙂
KC

Replies

That depends on what you want to do with the initilization. You may need all, or you may need none. What do you want to do?

Just some simple properties.
For now, all I need is a lable that will store a String, some representation to store a background color, and a boolean to store a state (in order to display the correct background color).
I might expand its functionality later, but the above is all I need at this point.

You can add some properties to your custome class and other things can be set up in the storyboard.

Do you have any reason you cannot use prototype cells?

If you have defined a custom xib for the cell, you should use awakeFromNib()

In such a case, you need to register the cell:

let nib = UINib(nibName: "MyCell", bundle: nil)

tableView.register(nib, forCellReuseIdentifier: "MyCell")



Otherwise, it depends on what you want:

- define a specific frame: use init(frame: CGRect)

- just general initialize : use init?(coder aDecoder:NSCoder)


But you can usually define the 3 init

    override init(frame: CGRect) {
        super.init(frame: frame)
       // initialize what is needed
    }
 
    required init?(coder: NSCoder) {
        super.init(coder: coder)
     
        self.isUserInteractionEnabled = true
       // initialize what is needed
    }
 
    override func awakeFromNib() {
        super.awakeFromNib()
       // initialize what is needed
    }