I know there is a post:adding to UICollectionViewCell contentView via nib asking this, but the answer is not correct. Dragging a UILabel directly into a cell's xib, the Label will be added into cell itself, not its 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>(
)
This is still true on XCode 7, sample: https://github.com/liuxuan30/autolayoutProblemOniOS9.
So I asked it again for a good answer.
The behaviour is different from UITableViewCell, which will show up a contentView in xib directly. Not sure why Apple did this, and saying in UICollectionViewCell doc https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewCell_class/:
To configure the appearance of your cell, add the views needed to present the data item’s content as subviews to the view in the contentView property. Do not directly add subviews to the cell itself.
After contacting Apple's technical support, they told me it will be added in cell's contentView if it's via xib, but won't if I program it, unless I manually add them as cell.contentView's subView.
One thing to mention is that, if we add sub views via xib but it does not belongs to contentView, we need to delete the view on xib and drag a new UICollectionViewCell onto xib. The contentView will not show up on xib, this is different from UITableViewCell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With