在Storyboard中设计UICollectionViewCell

11

我以前从未使用过UICollectionViewController,我认为它们与UITableViewController有些相似,但令我惊讶的是,我不能像自定义UITableViewCell一样向自定义UICollectionViewCell添加UI元素。

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

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

我做错了什么?


可能是http://stackoverflow.com/questions/18201574/uicollectionview-dont-show-the-cell/18201639#18201639的重复问题。请查看我的答案。虽然不完全相同,但我的答案可以解决你的问题。 - rdelmar
@rdelmar 非常感谢!这解决了问题! - neutrino
3个回答

31

完整的解释在这里

为UICollectionViewCell创建一个自定义类:

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    // have outlets for any views in your storyboard cell
    @IBOutlet weak var myLabel: UILabel!
}
在Storyboard中,将单元格使用这个类,并为单元格设置标识符。在viewDidLoad中不要使用registerClass...forCellWithReuseIdentifier,但你会在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类。


如何将自定义类中的标签与故事板连接? - Zeeshan Shabbir
@ZeeshanShabbir,在Storyboard中从标签控件拖动到代码中的@IBOutlet标签。 - Suragch
当我这样做时,我可以看到我放在自定义单元格中的内容,但是单元格的选择根本没有触发。如果我使用registerClass设置,那么我可以检测到您点击单元格的操作,但是我在storyboard中放置的标签没有连接。(这很有道理,因为我没有注册storyboard版本)。如何使用此示例中显示的设置使选择功能正常工作?(注意:我的ViewController中有两个collectionViews-另一个使用xib文件,因为它具有更复杂的内容。) - N.W
更新 - 当我将我的单元格放入xib中时,我能够使选择和单元格上的标签都正常工作。我怀疑这是xcode故事板中的一个错误。我正在使用Xcode 12.2。 - N.W

4

@Suragch说得对。我也遇到了这个问题:当我的UICollectionViewCell原型在绘制时,其内容未显示在单元格中。

关键的一行是:“不要在viewDidLoad中使用registerClass...forCellWithReuseIdentifier”。确实,不要这样做。不仅“没有必要”,而且“如果你注册,它会阻止你的单元格原型正常加载”。

这仅适用于基于Storyboard的代码,而不是.xib-based。


1
如果你想使用registerClass...forCellWithReuseIdentifier,那么你应该这样做:
let nib = UINib(nibName: "TrackCollectionViewCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: "trackCellIdentifier")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接