UICollectionViewCell寄存器类失败,但注册nib工作

Jas*_*ges 12 uicollectionview uicollectionviewcell swift

UICollectionViewCell为我创建一个自定义UICollectionViewController,它通过注册笔尖来工作; 但是,没有按班级注册.

使用registerClass() - 失败

按类注册似乎是正确的 - 它构建,但在运行时抛出异常,从UIView中解开可选元素.没有引用插座,它运行; 但是,集合视图中不会出现单元格.

collectionView?.registerClass(MyCollectionViewCell.self, 
                              forCellWithReuseIdentifier: "myCell")
Run Code Online (Sandbox Code Playgroud)

很明显,视图没有加载; 但是,我认为设置单元格的自定义类将提供必要的链接.

使用registerNib() - 工作

通过nib注册工作,这在显式加载视图时是有意义的.

let nib = UINib(nibName: "MyCollectionViewCell", bundle: nil)
collectionView?.registerNib(nib, forCellWithReuseIdentifier: "myCell")
Run Code Online (Sandbox Code Playgroud)

这里明确引用了视图,并为视图设置了自定义类; 然而,关于这一点似乎是错误的.

示例项目

隔离示例项目中的问题,下面是要复制的视图和代码; 或者,这个项目可以在GitHub上找到.

Main.storyboard

我的主要故事板初始视图控制器是一个UICollectionViewController子类MyCollectionViewController:

UICollectionViewController

MyCollectionViewController.swift

显示由笔尖和按类注册:

import UIKit

class MyCollectionViewController: UICollectionViewController {

    var data = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        data = ["a", "b", "c"]

        // This works, by nib
        let nib = UINib(nibName: "MyCollectionViewCell", bundle: nil)
        collectionView?.registerNib(nib, forCellWithReuseIdentifier: "myCell")

        // This fails, by class
        //collectionView?.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! MyCollectionViewCell

        cell.title.text = data[indexPath.row]

        return cell
    }

}
Run Code Online (Sandbox Code Playgroud)

MyCollectionViewCell.xib

查看是UICollectionViewCell子类为MyCollectionViewCell具有UILabel:

MyCollectionViewCell

在我的笔尖中,Collection Reusable View Identifier已设置为myCell:

MyCollectionViewCell标识符

MyCollectionViewCell.swift

定义类,并具有IBOutlet标签:

import UIKit

class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var title: UILabel!

}
Run Code Online (Sandbox Code Playgroud)

使用nib,执行显示为:

与iPhone 4S

为什么我不能UICollectionViewCell按班级注册?

同样,关于原型单元是否需要保留在主故事板集合视图控制器上,我有点模糊.在那里,我没有定义任何可重用的视图标识符.

vie*_* vu 17

我看到这个链接概述集合视图

如果单元类是用代码编写的,则使用UICollectionView的registerClass:方法执行注册.例如:[self.myCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"MYCELL"]; 如果单元格包含在Interface Builder NIB文件中,则使用registerNib:方法.

所以你的集合单元用nib创建,你应该用nib注册.如果您的单元格完全用代码编写,则需要在课堂上注册.

希望这有帮助.