通过 xib 或 storyboard 将子视图添加到 UICollectionViewCell 的 contentView
Posted
技术标签:
【中文标题】通过 xib 或 storyboard 将子视图添加到 UICollectionViewCell 的 contentView【英文标题】:add sub views into UICollectionViewCell's contentView via xib or storyboard 【发布时间】:2016-01-07 04:02:26 【问题描述】:我知道有一个帖子:adding to UICollectionViewCell contentView via nib问这个,但答案不正确。将 UILabel 直接拖到单元格的 xib 中,Label 将添加到单元格本身,而不是其 contentView:
(lldb) po self.subviews
<__NSArrayM 0x7fa9b1c58a20>(
<UIView: 0x7fa9b1c77540; frame = (0 0; 64 64); gestureRecognizers = <NSArray: 0x7fa9b1c66260>; layer = <CALayer: 0x7fa9b1c352f0>>,
<UILabel: 0x7fa9b1c7a880; frame = (0 15; 64 18); text = 'market share'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fa9b1c6f820>>,
<UILabel: 0x7fa9b1c77c30; frame = (0 38; 64 22); text = '17.06'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fa9b1c36fe0>>
)
(lldb) po self.contentView.subviews
<__NSArray0 0x7fa9b1d02740>(
)
在 XCode 7 上仍然如此,示例:https://github.com/liuxuan30/autolayoutProblemOnios9。
所以我又问了一个好答案。
该行为与 UITableViewCell 不同,它将直接在 xib 中显示一个 contentView。不知道苹果为什么这样做,并在 UICollectionViewCell doc https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewCell_class/ 中说:
要配置单元格的外观,请将显示数据项内容所需的视图作为子视图添加到 contentView 属性中的视图。不要直接将子视图添加到单元格本身。
【问题讨论】:
【参考方案1】:联系Apple的技术支持后,他们告诉我如果是通过xib,它将被添加到cell的contentView中,但如果我对其进行编程则不会,除非我手动将它们添加为cell.contentView的subView。
需要说明的是,如果我们通过xib添加子视图但它不属于contentView,我们需要删除xib上的视图并将新的UICollectionViewCell拖到xib上。 contentView 不会显示在 xib 上,这与 UITableViewCell 不同。
【讨论】:
以上是关于通过 xib 或 storyboard 将子视图添加到 UICollectionViewCell 的 contentView的主要内容,如果未能解决你的问题,请参考以下文章
MacOS-MacAPP通过纯代码不依赖storyboard/xib加载UI主界面
Xcode中不用Storyboard,用纯xib创建TabBar模式视图
Xcode 5 - iOS - 如何在没有 Storyboard 或 XIB 的情况下在 Xcode 中创建视图控制器以及如何将其配置为 AppDelegate 作为根视图