2016-02-29 56 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];