Ios 在故事板中设计UICollectionViewCell

Ios 在故事板中设计UICollectionViewCell,ios,objective-c,uicollectionview,uicollectionviewcell,Ios,Objective C,Uicollectionview,Uicollectionviewcell,我从未使用过UICollectionViewControllers,我认为它们有点类似于UITableViewControllers,但令我惊讶的是,我不能像使用customUITableViewCells那样向自定义UITableViewCells添加UI元素 事实上,我可以在界面生成器中添加标签、按钮等,但当我运行应用程序时,单元格显示为空 我已通过调用(void)registerClass:(class)cellClass forCellWithReuseIdentifier:(NSStr

我从未使用过
UICollectionViewController
s,我认为它们有点类似于
UITableViewController
s,但令我惊讶的是,我不能像使用custom
UITableViewCell
s那样向自定义
UITableViewCell
s添加UI元素

事实上,我可以在界面生成器中添加标签、按钮等,但当我运行应用程序时,单元格显示为空

我已通过调用
(void)registerClass:(class)cellClass forCellWithReuseIdentifier:(NSString*)identifier在
viewDidLoad
方法期间注册了cell类,并且我已检查是否在
(UICollectionViewCell*)collectionView中返回了
UICollectionViewCell
的有效实例:(UICollectionView*)collectionView单元格ForItemAtIndexPath:(NSIndexPath*)indexPath
方法

我做错了什么?

我的完整解释是

为UICollectionViewCell创建自定义类:

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    // have outlets for any views in your storyboard cell
    @IBOutlet weak var myLabel: UILabel!
}
在情节提要中,使单元使用此类

并设置单元格的标识符

不要在
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类。

@Suragch很合适。我也遇到了这个问题:我的UICollectionViewCell原型在绘制时没有在单元中显示内容

关键的一行是:“不要在viewDidLoad中使用registerClass…forCellWithReuseIdentifier”。真的,不要。不仅仅是“没有必要”,而是“如果你注册,它会阻止你的细胞原型正常加载”


这只适用于基于故事板的代码,而不是基于.xib的。

如果您想使用registerClass…forCellWithReuseIdentifier,那么您应该这样做:

let nib = UINib(nibName: "TrackCollectionViewCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: "trackCellIdentifier")

可能重复。请参见我的答案。这不是完全相同的问题,但我的答案会解决您的问题。@rdelmar非常感谢!这解决了问题!如何将自定义类中的标签连接到故事板?@ZeeshanShabbir,控制从故事板中的标签拖动到代码中的
@IBOutlet
标签。执行此操作时,我可以看到我在自定义单元格中放置的内容,但单元格的选择根本不会触发。如果我使用
registerClass
设置,那么我可以检测到你点击单元格的时间,但我在故事板中放置的标签没有连接。(这很有意义,因为我没有注册故事板版本)。如何使选择与本例中所示的设置一起使用?(注意:我的ViewController中有两个CollectionView-另一个使用xib文件,因为它有更复杂的内容。更新-当我将单元格放入xib中时,我能够使单元格上的选择和标签都起作用。我怀疑这是xcode情节提要中的错误。我使用的是xcode 12.2。