ios - 将 subview 添加到占据整个单元格框架的 UICollectionViewCell

标签 ios objective-c uicollectionview uicollectionviewcell

我正在尝试简单地将 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/

相关文章:

objective-c - 在 Objective C 中使用相机扫描 QR Code 或 BarCode

ios - 将水平 UICollectionView 中的一个单元格固定到右侧

ios - 每当我在任何按钮(即 UISegmentedControl 按钮)外单击时,按钮也会被单击。谁能告诉我为什么会这样?

objective-c - iPad : How to know Return key of iPad keyboard is pressed ? 请检查图像

objective-c - 如何保留我自己的对象和属性

ios - 使用 didSelectItemAtIndexPath 时是否可以访问不等于索引路径的所有单元格?

ios - 在启用 native 分页的情况下查看 UICollectionView 中的上一个/下一个单元格?

手动操作 navigationController 的 viewControllers 数组时 iOS 手机崩溃

ios - 我的 Xcode 8 有什么问题?我什至无法编译新项目?

objective-c - 将 NSCell 设置为 NSUinteger 值时避免隐式转换警告的正确方法?