在UICollecitonView中通过NIB添加自定义单元格

时间:2016-03-02 20:49:37

标签: ios swift uicollectionview nib

我有一个非常简单的swift程序,使用在UICollectionView中使用Nib构建的自定义单元格。

当我运行应用程序时,我收到一条错误说明

  

:由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:'无法在捆绑中加载NIB:"

我已经查看过所有教程并完全按照它们进行操作,看起来我似乎错过了一个初始化程序,但我感到很茫然。在故事板编辑器的CollectionViewController中的主默认单元格中,我将重命名标识符命名为#34; Cell",对于Nib(swift文件名为CustomCollectionViewCell.xib),我将重命名标识符命名为#34; CustomCell&#34 ;。我在Xib中有一个UIButton作为一个动作,如果按下它应该记录成功。

这是mainVC:

class MainCollectionViewController: UICollectionViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false


    // Register cell classes
    self.collectionView!.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "Cell")

    // Do any additional setup after loading the view.
}

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return 1
}

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

    // Configure the cell

    return cell
}
}

这是CustomCollectionViewCell代码:

class CustomCollectionViewCell: UICollectionViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}


@IBAction func testButton(sender: UIButton) {
    print("Success!")
}

}

我知道这是一个基本的,初学者的项目,但我已经在网络上的任何地方看到了并且感到难过。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

为什么不使用原型细胞。将原型单元格的类更改为CustomCollectionViewCell,在该单元格中设置UI。删除:

self.collectionView!.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "Cell")

在viewDidLoad中删除CustomCollectionViewCell.xib

相关问题