ios - 更改 UICollecionViewCell 之间的空间

标签 ios objective-c uicollectionview uicollectionviewcell uicollectionviewlayout

我有一个 CollectionView。这是我的 CollectionView 的实现。

- (void)setupCollectionView{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [self.flowLayout setSectionInset:UIEdgeInsetsMake(0, 20, 0, 0)];
    self.flowLayout.itemSize = CGSizeMake(150, 35);
    self.flowLayout.minimumLineSpacing = 20;
    [self.flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];

    self.vwCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.vwQuickReplyContainer.frame.size.width, self.vwQuickReplyContainer.frame.size.height) collectionViewLayout:self.flowLayout];
    self.vwCollectionView.backgroundColor = [UIColor clearColor];
    [self.vwCollectionView registerNib:[UINib nibWithNibName:@"QuickrepliesCell" bundle:nil] forCellWithReuseIdentifier:@"QuickrepliesCell"];
    [self.vwQuickReplyContainer addSubview:self.vwCollectionView];
    self.vwQuickReplyContainer.hidden = YES;
    [self.vwCollectionView setShowsHorizontalScrollIndicator:NO];

    [self.vwCollectionView setDataSource:self];
    [self.vwCollectionView setDelegate:self];
    [self.vwCollectionView reloadData];
}

这里我设置了 minimumLineSpacing 来设置连续列之间的最小间距。根据this documentation ,我知道该值表示水平滚动网格的连续列之间的最小间距。我还设置了单元格之间的空间。这是这样做的结果 enter image description here .

但为了更好看。我想根据内容的大小更改单元格的宽度。所以我已经像这样更新了我的单元格的框架。

- (QuickrepliesCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"QuickrepliesCell" forIndexPath:indexPath];
    QuickReply *model = [[QuickReply alloc]initWithDictionary:self.quickRepliesArr[indexPath.row] error:nil];
    self.cell.lblOpion.text = model.title;
    CGFloat width =  [self.cell.lblOpion.text sizeWithFont:WWLATOREGULAR(15)].width;
    self.cell.frame = CGRectMake(self.cell.frame.origin.x, self.cell.frame.origin.y, width + 24, self.cell.frame.size.height);
    return self.cell;
}

这是更新单元格宽度后的结果。 enter image description here .

我不知道更改单元格大小后更改单元格之间空间的原因。任何人都可以对此提出建议吗?谢谢。

最佳答案

不要将布局的 itemSize 属性设置为固定大小,而是实现 collectionView:layout:sizeForItemAtIndexPath: 布局委托(delegate)方法。

然后你就可以为每个项目设置合适的尺寸了。

关于ios - 更改 UICollecionViewCell 之间的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50753385/

相关文章:

ios - 小红色圆形删除按钮

iOS 需要帮助克服内存问题

android - Android/iPhone 图像识别

ios - 可以嵌套可重用的 UICollectionViewCells

iOS - 自动续订订阅到期

ios - 如何编码或隐藏 iOS 应用程序文件?

ios - 如何在 ios 中的自定义 UITableViewCell 中添加轮播 View

ios - 如何以编程方式选择 uitableview 单元格?

swift - 使用垂直无限滚动显示 UICollectionView 中的需求单元格

c# - 启用环绕的线性旋转木马