UICollectionViewCell subclass cannot use backgroundView property?

I made a subclass of UICollectionViewCell and Swift is complaining that I'm not allowed to use superclass properties like bounds, backgroundView or selectedBackgroundView. This very code was given by Appleʼs documentation so I don't understand why it's disallowed.

I declared class MyCollectionViewCell: UICollectionViewCell method awakeFromNib.

Code Block
class MyCollectionViewCell: UICollectionViewCell {
...
override class func awakeFromNib() {
...
let redView = UIView(frame: bounds)
redView.backgroundColor =  colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
self.backgroundView = redView
let blueView = UIView(frame: bounds)
blueView.backgroundColor =  colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)
self.selectedBackgroundView = blueView

Xcode 12.2 gives an error about bounds, backgroundView, and selectedBackgroundView saying stuff like "Instance member 'bounds' cannot be used on type 'MyCollectionViewCell'".

If I declare a variable as UICollectionViewCell I can set these properties in it, but a function in a subclass of UICollectionViewCell cannot access its own properties?


Answered by OOPer in 654408022
The problem exists in this line:
Code Block
    override class func awakeFromNib() {

The method awakeFromNib() which you want to override is an instance method, not a class method.
Remove the keyword class:
Code Block
    override func awakeFromNib() {



I do not understand why Xcode points this line with proper diagnostics, you should better send a feedback about this.
Accepted Answer
The problem exists in this line:
Code Block
    override class func awakeFromNib() {

The method awakeFromNib() which you want to override is an instance method, not a class method.
Remove the keyword class:
Code Block
    override func awakeFromNib() {



I do not understand why Xcode points this line with proper diagnostics, you should better send a feedback about this.
Fascinating, and thank you. The code completion feature offers two variants of awakeFromNib (class and instance) and does not distinguish them. I'll double-check both of these flaws in the latest Xcode and will report them if they're unfixed.

It never occurred to me to notice the class keyword, although I did notice the error using the adjective "instance".
UICollectionViewCell subclass cannot use backgroundView property?
 
 
Q