在故事板中设计UICollectionViewCell

neu*_*ino 9 objective-c ios uicollectionview uicollectionviewcell

我从未使用过UICollectionViewControllers,我认为它们与UITableViewControllers 有些相似,但令我惊讶的是,我无法UICollectionViewCell像使用自定义UITableViewCells 那样将UI元素添加到自定义s中.

实际上,我可以在Interface Builder中添加标签,按钮等,但是当我运行应用程序时,单元格显示为空.

我已经注册了在细胞类viewDidLoad通过调用方法(void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier,我已经检查了我回国的有效实例UICollectionViewCell(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath方法.

我究竟做错了什么?

Sur*_*gch 23

我的完整解释在这里.

为UICollectionViewCell创建自定义类:

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    // have outlets for any views in your storyboard cell
    @IBOutlet weak var myLabel: UILabel!
}
Run Code Online (Sandbox Code Playgroud)

在故事板中使单元格使用此类

在此输入图像描述

并设置单元格的标识符

在此输入图像描述

不要使用registerClass...forCellWithReuseIdentifierin viewDidLoad.但是你会在下面提到它collectionView...cellForItemAtIndexPath:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell

    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor.yellowColor()

    return cell
}
Run Code Online (Sandbox Code Playgroud)

将故事板单元格中的视图连接到MyCollectionViewCell课堂.