【发布时间】:2019-09-03 11:07:00
【问题描述】:
我想从左到右排列单元格。所以我使用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];
单元格的宽度适合标签的宽度:
// 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);
}];
}
当有多个单元格时一切顺利:
但是,当只有一个单元格时,单元格位于中心:
如果我使用itemSize而不是estimatedItemSize,就可以了:
layout.itemSize = CGSizeMake(80, 30);
我真的很困惑。将单元格放在集合视图的中心不是我想要的,但我也想使用自动布局,以便单元格的宽度自行调整。
那么有什么办法可以避免呢?
【问题讨论】:
标签: ios objective-c uicollectionview autolayout