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

时间:2014-01-04 22:27:32

标签: ios objective-c 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);
}

4 个答案:

答案 0 :(得分:13)

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

menuItem.frame = cell.bounds;

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

menuItem.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

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

[cell.contentView addSubview:menuItem];
menuItem.frame = cell.contentView.bounds;

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

答案 1 :(得分:1)

在这种情况下,您只应与单元格的contentView进行交互。

UIView *menuItem = [UIView new];
menuItem.frame = cell.contentView.bounds;
menuItem.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:menuItem];

答案 2 :(得分:0)

这是Swift版本。

let menuItem = UIView.init()
menuItem.frame = cell.bounds
menuItem.backgroundColor = .green
cell.contentView.addSubview(menuItem)
menuItem.frame = cell.contentView.bounds

答案 3 :(得分:0)

Swift 5 Apple文档:

  1. var contentView:UIView 将单元格的自定义内容添加到的主视图。 配置单元格时,您可以将表示单元格内容的所有自定义视图添加到此视图。单元格对象将内容放入 此视图位于任何背景视图之前。
  2. var backgroundView:UIView? 显示在单元格其他内容后面的视图。 使用此属性将自定义背景视图分配给单元格。背景视图放置在内容视图及其框架的后面 会自动调整,以使其填充单元格的边界。

示例:

let template = UIView()
self.backgroundView = template
template.layer.cornerRadius = 10
template.backgroundColor = .white