UICollectionView 中的 IBOutlets 为零 - Swift

IBOutlets in UICollectionView are nil - Swift

当我打印我在 MyCell class 中声明的 IBOutlets 时,它们结果为零。

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

}

有没有其他方法我应该 initializing/registering MyCell class in viewDidLoad of ViewController?

在自定义单元格的 xib 中,您需要按住控制键从您的视图中拖动到文件所有者并将它们连接到它们的 IBOutlets。

如果您在单元格中使用 .xib,则必须使用 Control-Drag 从您的视图到文件所有者并连接它们来创建参考插座。

而不是:

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

使用:

self.seriesCollectionView.register(UINib(nibName: "MyCellXibName", bundle: nil), forCellWithReuseIdentifier: "MyCell")