如何使一个collectionViewCell自动resize只有身高?
我使用了collectionView的stream式布局自动化function
self.flow = [[UICollectionViewFlowLayout alloc] init]; self.flow.scrollDirection = UICollectionViewScrollDirectionVertical; self.flow.sectionInset = UIEdgeInsetsZero; self.flow.estimatedItemSize = CGSizeMake(320, 48);
我想要单元格将宽度的CollectionView(widthCell = widthCollectionView)
但我得到了整个大小的自动化工作。 我尝试玩内容压缩/拥抱优先 – 不起作用。
对于CollectionView的宽度等于320px,我得到了标签内容大小的单元格大小。
我的单元格看起来像
限制水平:H:| -8- [img(48)] – 8- [标签] -8- |
如何使autosize工作只为垂直而不是水平?
我find了解决scheme。
CollectionViewCell有一个委托preferredLayoutAttributesFittingAttributes
所以,这个函数将layoutAttributes设置为estimatedItemSize
你需要下一步(对于身高)
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes { UICollectionViewLayoutAttributes *attr = [super preferredLayoutAttributesFittingAttributes:layoutAttributes]; //Must be called CGRect frame = attr.frame; frame.size.width = layoutAttributes.size.width; //Key here attr.frame = frame; return attr; }
同样你可以做更喜欢大小,宽度,使高度不变(frame.size.height = layoutAttributes.size.height)。
如果你只是复制layoutAttributes和改变宽度,将没有任何效果!
你必须叫超级。
其实你在这里是与约束优先的问题。
要解决优先级约束问题,您应该更新imageView Leading priority
999
并以编程方式或直接从InterFace Builder label Trailing
优先级999
。
通过使用我已经实现的KVConstraintExtensionsMaster
以编程方式更新优先级,以更新没有IBOutlet reference
的Autolayout约束的任何约束。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell1" forIndexPath:indexPath]; [cell.imageView changeAppliedConstraintPriority:999 forAttribute:NSLayoutAttributeLeading]; [cell.label changeAppliedConstraintPriority:999 forAttribute:NSLayoutAttributeTrailing]; return cell; }
之后现在你需要计算单元格的唯一高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { CGFloat width = CGRectGetWidth(collectionView.bounds); CGFloat height = /* do here some calculation for height */ return CGSizeMake(width, height);; }
- UISplitViewController – 设置始终可见的主控制器
- iOS滚动视图,容器视图 – 自动布局问题
- UICollectionViewCell systemLayoutSizeFittingSize返回不正确的宽度
- 每当我的应用程序启动时,为什么我会在执行“-layoutSubviews”后仍然需要“自动布局”?
- 在UITableViewCell的子视图上设置遮罩层将覆盖自动布局约束
- 是否有可能在UIScrollView放大和缩小UIImageView,但坚持自动布局居中?
- 无法同时满足约束embedded在故事板中的AVPlayerViewController的警告
- 自动布局自动旋转时,如何重新排列视图?
- 只在iPhone中查看不显示在iPad中