我试图简单地将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);
}
答案 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文档:
示例:
let template = UIView()
self.backgroundView = template
template.layer.cornerRadius = 10
template.backgroundColor = .white