Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBOutlets in UICollectionView are nil - Swift

When I print the IBOutlets I declared in MyCell class, they come out to be nil.

Methods in ViewController

public override func viewDidLoad() {
    super.viewDidLoad()
    self.seriesCollectionView.register(MyCell.self, forCellWithReuseIdentifier: "MyCell")
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCell
    cell.setup()

    return cell
}

MyCell class

class MTSeriesViewCell: UICollectionViewCell {
@IBOutlet weak var cellView: UIView!

@IBOutlet weak var cellImageView: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
}

public func setup() {
    print(cellView)
}

}

Is there any other way I should be initializing/registering MyCell class in viewDidLoad of ViewController?

like image 652
Astha Gupta Avatar asked Aug 30 '25 16:08

Astha Gupta


2 Answers

Instead of:

self.seriesCollectionView.register(MyCell.self, forCellWithReuseIdentifier: "MyCell")

use:

self.seriesCollectionView.register(UINib(nibName: "MyCellXibName", bundle: nil), forCellWithReuseIdentifier: "MyCell")
like image 108
kamil3 Avatar answered Sep 03 '25 20:09

kamil3


In the xib for your custom cell you need to control-drag from you views onto file's owner and connect them to their IBOutlets.

like image 33
Duncan C Avatar answered Sep 03 '25 20:09

Duncan C