Defining UICollectionViewCell with nib

2019-01-23 14:57发布

问题:

If I understand correctly, the content of a UICollectionViewCell should go inside its contentView property and the background into backgroundView.

Yet, when I drag a UICollectionViewCell to Interface Builder there is no mention of contentView or backgroundView. If I add subviews, those will have the whole cell as its parent, not contentView or backgroundView.

What is the right way of defining a UICollectionViewCell with IB, then?

回答1:

"If I add subviews, those will have the whole cell as its parent, not contentView"

This is not true. If you drag in a UICollectionViewCell, and add UI elements to it, you are adding them to the content view. The fact that it doesn't show up in the objects list doesn't mean it's not there (the same is true for NSBox - it has a content view that doesn't show up in IB either). If in collectionView:didSelectItemAtIndexPath:, you log cellForItemAtIndexPath, and look at its subviews, you find only one, and it's the same one you get by logging cell.contentView. If you log its subviews, then you will see your UI elements.

Now, as far as background view, I don't think that's something you can access from IB. You can have a xib file with a UIView, and then assign that to the cell's backgroundView property.



回答2:

For lack of a better option, I'm using separate nib files for the contentView and the backgroundView. Then in my UICollectionViewCell subclass:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        NSArray *contentViewNib = [[NSBundle mainBundle] loadNibNamed:@"CollectionViewCellContentView" owner:self options:nil];
        [self.contentView addSubview:contentViewNib[0]];
        NSArray *backgroundViewNib = [[NSBundle mainBundle] loadNibNamed:@"CollectionViewCellBackgroundView" owner:self options:nil];
        self.backgroundView = backgroundViewNib[0];
    }
    return self;
}


回答3:

I'm not sure if this is new to Xcode 8 but UICollectionViewCell includes outlets for connecting the backgroundView and selectedBackgroundView.

Thanks to this, you can add a UIView (or subclass) to your collection view cell and connect it to either one of the outlets. This way you'll be able to define them using IB.

Hope this helps!