【问题标题】:Designing UICollectionViewCell in storyboard在情节提要中设计 UICollectionViewCell
【发布时间】:2015-01-14 15:56:07
【问题描述】:

我从未使用过UICollectionViewControllers,我认为它们与UITableViewControllers 有点相似,但令我惊讶的是,我无法以与我相同的方式将 UI 元素添加到我的自定义UICollectionViewCells使用自定义UITableViewCells。

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

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

我做错了什么?

【问题讨论】:

  • stackoverflow.com/questions/18201574/… 的可能重复项。在那里看到我的答案。这不是完全相同的问题,但我的回答会解决您的问题。
  • @rdelmar 非常感谢!这样就解决了问题!

标签: ios objective-c uicollectionview uicollectionviewcell


【解决方案1】:

我的完整解释是here

为 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 类。

【讨论】:

  • 如何将自定义类中的标签连接到故事板?
  • @ZeeshanShabbir,控制从情节提要中的标签拖动到代码中的@IBOutlet标签。
  • 执行此操作时,我可以看到我在自定义单元格中放入的内容,但单元格的选择根本没有触发。如果我使用registerClass 设置,那么我可以检测到您何时点击了一个单元格,但我在情节提要中放置的标签未连接。 (这是有道理的,因为我没有注册故事板版本)。如何让选择与本示例中显示的设置一起使用? (注意:我的 ViewController 中有两个 collectionViews - 另一个使用 xib 文件,因为它有更复杂的内容。
  • 更新 - 当我将我的单元格放入 xib 时,我能够让单元格上的选择和标签工作。我怀疑这是 xcode 故事板中的错误。我正在使用 Xcode 12.2。
【解决方案2】:

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

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

这仅适用于基于 Storyboard 的代码,不适用于基于 .xib 的代码。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-01-20
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多