当只有一个单元格时,单元格位于集合视图的中心

无夜之*_*之星辰 3 objective-c ios autolayout uicollectionview

我想从左到右布局单元格。所以我使用UICollectionViewFlowLayout

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
// use this for let cell width fit for label width
layout.estimatedItemSize = CGSizeMake(80, 30);
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
Run Code Online (Sandbox Code Playgroud)

单元格的宽度适合标签的宽度:

// cell code
@implementation CQGoodsSearchCell

- (void)setupUI {
    self.contentView.layer.cornerRadius = 15;
    self.contentView.layer.masksToBounds = YES;
    self.contentView.backgroundColor = [UIColor colorWithRed:1.00 green:1.00 blue:1.00 alpha:1.00];

    self.nameLabel = [[UILabel alloc] init];
    [self.contentView addSubview:self.nameLabel];
    self.nameLabel.font = [UIFont systemFontOfSize:15];
    self.nameLabel.textColor = [UIColor colorWithRed:0.18 green:0.18 blue:0.18 alpha:1.00];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(10);
        make.right.mas_offset(-10);
    }];
}
Run Code Online (Sandbox Code Playgroud)

当有多个单元格时,一切顺利:

左对齐的两个单元格

但是,当只有一个单元格时,单元格位于中心:

中心的一个单元格

如果我使用itemSize而不是estimatedItemSize,那就可以了:

layout.itemSize = CGSizeMake(80, 30);
Run Code Online (Sandbox Code Playgroud)

一旦单元格向左对齐

我真的很困惑。将单元格放在集合视图的中心不是我想要的,但我也想使用自动布局,以便单元格的宽度自行调整。

那么有没有办法避免这种情况呢?

kam*_*ing 7

选择none在预计大小选项。如果集合视图只有一项,它将左对齐而不是居中。

在此处输入图片说明


mat*_*att 3

基本上这与我在这里讨论的问题相同:

/sf/answers/3670003221/

总之,您尝试使用的功能(自调整大小的集合视图单元格)不起作用并且从未起作用。这就是为什么,正如你所说,

如果我用itemSize代替的话estimatedItemSize,就可以了

这是正确的!这不是你的错误;而是你的错误。这是一个 iOS 错误。自动调整集合视图单元格大小不起作用。应用程序崩溃或流程布局不正确。

这就是解决方案。不使用estimatedItemSize。相反,您自己计算正确的大小并在您的实现中提供它

func collectionView(_ collectionView: UICollectionView, 
    layout collectionViewLayout: UICollectionViewLayout, 
    sizeForItemAt indexPath: IndexPath) -> CGSize {
        // calculate/obtain correct size and return it
}
Run Code Online (Sandbox Code Playgroud)