将子视图添加到占用整个单元框架的UICollectionViewCell

DBo*_*yer 11 objective-c ios uicollectionview uicollectionviewcell

我试图简单地将UIView添加到占据整个单元框架的UICollectionViewCell.我现在的代码只在左上角显示一个单元格(我怀疑每个单元格在彼此的顶部进行分层).我怎么能这样做?

我计划稍后再继承UIView,以便自定义我添加到单元格的视图.我不想基于我将使用它的方式继承UICollectionViewCell.

#pragma mark - Collection view data source

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    UIView *menuItem = [[UIView alloc] init];
    menuItem.frame = cell.frame;
    menuItem.backgroundColor = [UIColor greenColor];
    [cell addSubview:menuItem];

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; {
    return CGSizeMake(60, 60);
}
Run Code Online (Sandbox Code Playgroud)

Aar*_*ger 13

你需要使用bounds,而不是frame.如果你不知道这两者之间的区别或为什么这很重要,你应该阅读这篇文章并在进一步说明之前先熟悉它:

menuItem.frame = cell.bounds;
Run Code Online (Sandbox Code Playgroud)

您还需要设置自动调整遮罩,因为单元格最初的大小不正确:

menuItem.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
Run Code Online (Sandbox Code Playgroud)

而且,实际上,您应该将其添加到单元格的contentView属性中:

[cell.contentView addSubview:menuItem];
menuItem.frame = cell.contentView.bounds;
Run Code Online (Sandbox Code Playgroud)

也就是说,如果您计划添加大量子视图menuItem,我建议继承UICollectionViewCell而不是尝试在您的cellForItemAtIndexPath:方法中构建它.如果布局和设置封装在不同的类中,则更容易控制,并且您可以通过覆盖来响应高度/宽度更改layoutSubviews.