在故事板中设计UICollectionViewCell

时间:2015-01-14 15:56:07

标签: ios objective-c uicollectionview uicollectionviewcell

我从未使用UICollectionViewController,我认为它们与UITableViewController有些相似,但令我惊讶的是,我无法将UI元素添加到我的自定义UICollectionViewCell中与我对自定义UITableViewCell的方式相同。

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

我通过调用viewDidLoad(void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier方法中注册了单元格类,并且我已经检查过我在{{1}中返回了UICollectionViewCell的有效实例方法。

我做错了什么?

3 个答案:

答案 0 :(得分:17)

我的完整解释是here

为UICollectionViewCell创建自定义类:

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    // have outlets for any views in your storyboard cell
    @IBOutlet weak var myLabel: UILabel!
}

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

enter image description here

并设置单元格的标识符

enter image description here

请勿使用registerClass...forCellWithReuseIdentifier中的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
}

将故事板单元格中的视图中的插座连接到MyCollectionViewCell类。

答案 1 :(得分:1)

@Suragch在现场。我也有这个问题:绘制时,UICollectionViewCell原型的内容未显示在单元格中。

关键行是:“不要在viewDidLoad中使用registerClass ... forCellWithReuseIdentifier。”真的,不要。不仅“没有必要”,而且“如果您进行注册,它将使您的细胞原型无法正确加载”。

这仅适用于基于情节提要的代码,不适用于基于.xib的代码。

答案 2 :(得分:0)

如果要使用registerClass ... forCellWithReuseIdentifier,则应采用以下方式:

# works fine
nums <- c("mpg", "disp", "cyl")
mtcars %>% group_by(carb) %>% summarise(cnt = n())