我正在尝试简单地将 UIView 添加到占据整个单元格框架的 UICollectionViewCell。我现在的代码只在左上角显示一个单元格(我怀疑每个单元格都在彼此重叠)。我到底该怎么做?
我计划稍后对 UIView 进行子类化,以便自定义要添加到单元格的 View 。我不想将 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);
}
最佳答案
您需要使用bounds
,而不是frame
。如果您不知道两者之间的区别或为什么这很重要,您应该在进一步阅读之前阅读并熟悉它:
menuItem.frame = cell.bounds;
您还需要设置一个自动调整大小的掩码,因为单元格最初不会处于正确的大小:
menuItem.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
而且,实际上,您应该将其添加到单元格的 contentView
属性中:
[cell.contentView addSubview:menuItem];
menuItem.frame = cell.contentView.bounds;
也就是说,如果您计划向 menuItem
添加大量 subview ,我建议继承 UICollectionViewCell 而不是尝试在您的 cellForItemAtIndexPath:
方法中构建它。如果将布局和设置封装在不同的类中,将更容易控制,并且您可以通过覆盖 layoutSubviews
来响应高度/宽度的变化。
关于ios - 将 subview 添加到占据整个单元格框架的 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927522/