I want to layout cells from left to right.So I use 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];
The cell's width is fit for the label's width:
// 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);
}];
}
Everything gose well when there is more than one cell:
However,the cell is in the center when there is only one cell:
If I use itemSize
instead of estimatedItemSize
, it is OK:
layout.itemSize = CGSizeMake(80, 30);
I am really confused about this. Having the cell in the center of the collection view is not what I want but I also want to use Auto Layout so the cell's width adjusts itself.
So is there any way to avoid this?