我从未使用UICollectionViewController
,我认为它们与UITableViewController
有些相似,但令我惊讶的是,我无法将UI元素添加到我的自定义UICollectionViewCell
中与我对自定义UITableViewCell
的方式相同。
事实上,我可以在Interface Builder中添加标签,按钮等,但是当我运行应用程序时,单元格显示为空。
我通过调用viewDidLoad
在(void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier
方法中注册了单元格类,并且我已经检查过我在{{1}中返回了UICollectionViewCell
的有效实例方法。
我做错了什么?
答案 0 :(得分:17)
我的完整解释是here。
为UICollectionViewCell创建自定义类:
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
// have outlets for any views in your storyboard cell
@IBOutlet weak var myLabel: UILabel!
}
在故事板中,让单元格使用此类
并设置单元格的标识符
请勿使用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())