无夜之*_*之星辰 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)
我真的很困惑。将单元格放在集合视图的中心不是我想要的,但我也想使用自动布局,以便单元格的宽度自行调整。
那么有没有办法避免这种情况呢?
基本上这与我在这里讨论的问题相同:
总之,您尝试使用的功能(自调整大小的集合视图单元格)不起作用并且从未起作用。这就是为什么,正如你所说,
如果我用
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)
| 归档时间: |
|
| 查看次数: |
1038 次 |
| 最近记录: |