问题 将子视图添加到占用整个单元框架的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);
}

10764
2018-01-04 22:27


起源

你可以将menuItem.frame = cell.frame更改为menuItem.frame = cell.bounds - kkocabiyik


答案:


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

menuItem.frame = cell.bounds;

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

menuItem.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

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

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

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


13
2018-01-04 23:32



好吧也许你是对的。感谢您提供的所有帮助,我认为我将按照您的建议继承UICollectionViewCell。 - DBoyer
自动调整面具的好建议...我一直试图解决这个问题(最初的错误大小调整),而现在......谢谢! - shokaveli
我现在遇到了可重复使用的单元的问题...如果我将子视图添加到单元格编号1,那么iOS会重复使用它,它会出现在单元格17或18中。任何解决方案? - Script Kitty
@script kitty表格单元格如何工作...如果你添加一个视图,它将一直保留在那里,直到你改变或删除它 - Aaron Brager
我最终清理了prepareForReuse方法中的视图。感谢您的回答! - Script Kitty


你应该只与细胞进行交互 contentView 在这种情况下。

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

1
2018-01-04 23:31