【问题标题】:Subclassing UICollectionViewCell with a custom xib and contentView使用自定义 xib 和 contentView 子类化 UICollectionViewCell
【发布时间】:2015-12-26 06:58:10
【问题描述】:

我使用 File > New > File... > Cocoa Touch Class 的 Xcode UI 创建了我的子类(同时检查了创建 xib 文件)... 完成。

我将子视图直接添加到集合视图单元格的view 子视图中:

我已经用UICollectionView 注册了子类和笔尖,一切都很好。但是,当我以编程方式访问我的集合视图单元格的 contentView 属性来设置其背景颜色时,它并没有改变。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifiers.Category, forIndexPath: indexPath) as! CategoryCollectionViewCell

    let category = categoryForIndexPath(indexPath)

    cell.textLabel.text = titleForCategory(category)

    cell.contentView.backgroundColor = UIColor.redColor()

    return cell
}

在 lldb 中,我的 contentView 的地址是:0x13fdc3550,而文本标签的超级视图(我认为应该是 contentView)的地址是 0x000000013fdc36b0 -所以它们一定是不同的。

如何使用自定义 xib 成功继承 UICollectionViewCell 并通过 contentView 属性访问内容视图?

P.s,有趣的是,如果我将这个 contentView 属性的 hidden 设置为 true,就可以了。

【问题讨论】:

  • 尝试在collectionView(_:willDisplayCell:forItemAtIndexPath:)中设置背景色
  • 很遗憾这不起作用

标签: ios xib uicollectionviewcell


【解决方案1】:

Text Label 的 superView 是你拖入单元格的UIView。它应该是单元格内容视图的子视图。因此,当您将 contentView 的 hidden 设置为 true 时,它​​的子视图也会被隐藏。但是,当您将 contentView 的 backgroundColor 设置为某些内容时,您拖入单元格的视图将覆盖它。您可以检查文本标签的superview的superview,看它是否与lldb中contentView的地址匹配。

因此,您可以在此处直接更改该视图的背景颜色或更改单元格的布局删除该视图。

【讨论】:

  • 我没有拖出textLabel的superview。但这仍然应该是相同的逻辑吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2021-09-23
  • 2013-01-06
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
相关资源
最近更新 更多