2016-02-29 59 views
0

我有一个集合视图固定到它的超级视图的底部,左侧和右侧边缘,并且文本字段固定到超级顶部,左侧和右侧。 updateConstraints从下到上增加了集合视图的高度,其中基于其内容大小的高度约束随着更多项目的添加而增加。使用不等式约束和优先级限制UICollectionView高度

我希望集合视图高度增长但不超过 上方的textField的底部,并在 集合视图的顶部边缘有一个不等式约束。以下是我已经试过:

self.topResistanceConstraint = [NSLayoutConstraint constraintWithItem:self.collectionView 
    attribute:NSLayoutAttributeTop 
    relatedBy:NSLayoutRelationGreaterThanOrEqual 
    toItem:self.textField 
    attribute:NSLayoutAttributeBottom 
    multiplier:1.0 
    constant:0]; 
[self addConstraint:self.topResistanceConstraint]; 

CGSize size = self.collectionView.collectionViewLayout.collectionViewContentSize; 

self.heightConstraint = [NSLayoutConstraint constraintWithItem:self.collectionView 
attribute:NSLayoutAttributeHeight 
    relatedBy:NSLayoutRelationEqual 
    toItem:nil 
    attribute:NSLayoutAttributeNotAnAttribute 
    multiplier:1.0 
    constant:size.height]; 
[self addConstraint:self.heightConstraint]; 

这将导致不可满足的约束,并恢复(实际上似乎工作),但它不是一个很好的解决方案,如果布局需要适应键盘不起作用出现或消失。任何建议如何创建约束或优先级,以使其在不受约束的情况下工作?

回答

0

此问题的首选解决方案是为故事板中的collectionView创建高度和顶部约束 (顶部约束与“NSLayoutRelationGreaterThanOrEqual”相关),并为两者创建出口。 之后获得的CollectionView项目数比动态计算的CollectionView的高度如下

NSInteger count = 5; 
CGFloat collectionViewHeight = count/2 * cellHeight; // for collectionView with two(2) columns 
CGFloat maxCollectionViewHeight = CGRectGetHeight(self.view.frame) - CGRectGetHeight(self.textField.frame) - CGRectGetMaxY(self.textField.frame); 
if (collectionViewHeight < maxCollectionViewHeight) { 
    self.heightConstraint.constant = collectionViewHeight; 
} else { 
    self.topConstraint.constant = 20; // Min spacing between two views; 
} 
+0

大小已经用self.collectionView.collectionViewLayout.collectionViewContentSize计算出来了。我想完成的是消除模糊布局,同时使顶部约束优先于高度约束。 – user1192805

1

一些试验和错误后,只需设置heightConstraint低优先级效果很好。 topResistanceConstraint的优先级是必需的,并防止收集视图的顶部超过文本字段的底部。

self.heightConstraint = [NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeHeight 
    relatedBy:NSLayoutRelationEqual 
    toItem:nil 
    attribute:NSLayoutAttributeNotAnAttribute 
    multiplier:1.0 
    constant:size.height]; 

// set a low priority on height 
self.heightConstraint.priority = UILayoutPriorityLow; 

[self addConstraint:self.heightConstraint];