ios - 从 nib 加载 UICollectionViewCell 而不重用

标签 ios swift uicollectionview

我有一个带有 Nib 的自定义 UICollectionViewCell,我想将其加载到 UICollectionView 的 cellForItemAt 方法中,但不从 Collection View 的 dequeueReusableCell 方法中获取/实例化单元格。

我遇到的问题是,当像这样简单地加载单元格时:

let cell = MyCustomCell()

它的 IB 属性没有加载,我也试过调用:

cell.awakeFromNib() and/or layoutIfNeeded()

没有效果。我可以使用 dequeue 方法从 IB 加载 View ,但如上所述,不能使用它。

我在 Collection View 所在的 View Controller 的 viewDidLoad 中正确注册了 Nib :

let name = String(describing: MyCustomCell.self)
collectionView.register(
    UINib(
        name: name,
        bundle: nil),
    forCellWithReuseIdentifier: "customCell")

最佳答案

IBOutlets 不能在您的 MyCustomCell 实例上工作的原因是因为只有类被实例化,而不是 xib/nib。 当您在 tableView 中注册一个单元格然后使该单元格出队时,这两个单元格都会被初始化,这就是神奇发生的地方。

如果你真的想在不使用 tableview 的 dequeue 方法的情况下加载一个单元格,你可以这样做:

  1. 为您的 UITableViewCell 自定义类创建一个 var,在本例中为 MyCustomCell

    var notReusableCell:CellTableViewCell?
    
  2. 在 viewDidLoad 中获取 nib 并获得您想要的 View ,在这种情况下我们需要单元格,以便它成为第一个 View 。

    let nib = Bundle.main.loadNibNamed("CellTableViewCell", owner: self, options: nil) notReusableCell = nib?.first as! CellTableViewCell?

  3. 现在在您的 cellForRowAt 方法中传递存储在您的 var 中的单元格

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = notReusableCell else { return CellTableViewCell() } 返回单元格 }

请修改您正在尝试做的事情,因为这种做法并不常见。

关于ios - 从 nib 加载 UICollectionViewCell 而不重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44557560/

相关文章:

ios - Grouped Table View 发送 nil 但 Plain 完美运行

ios - 如何使用 IMA SDK 快速播放带 MPMoviePlayerController 的前置视频广告

objective-c - 正确使用 Objective C++

ios - 将 12 位数字刻度转换为日期

ios - 覆盖 UITableViewController 子类中的 cellForRowAtIndexPath 返回错误 : does not override any method from superclass

ios - 应用 CAGradientLayer 到 layer.borderColor

ios - 自动调整 UITableView 中嵌入的 UICollectionView 单元格大小不起作用

ios - 如何使用 Swift 4 在 UICollection View 中获得多个选择

ios - 不允许应用程序访问 UDID,也不允许使用 UIDevice 的 uniqueIdentifier 方法

iOS: Collection View ,selectItemAtIndexPath 以编程方式不起作用