【发布时间】:2013-12-18 10:43:41
【问题描述】:
我在添加 NSLayoutConstraint 时遇到问题。我想更新 UICollectionView 的高度,以便所有单元格都适合 UICollectionView 而无需滚动。这是因为我将 UICollectionView 与其他 UI 元素一起放在了 UIScrollView 中。
我已经在界面构建器中设置了约束,当我知道应该显示多少项目时,我在 viewDidLoad 上调整了 UICollectionView 的大小。我这样做是用
[self allBooksCollectionViewSetConstraints];
我已经设置了
[allBooksCollectionView setTranslatesAutoresizingMaskIntoConstraints:NO];
这是我的代码
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation) fromInterfaceOrientation {
[self allBooksCollectionViewConstraints];
}
-(NSInteger)allBooksCollectionViewHeight
{
float booksPerRow;
if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
booksPerRow = 6.0;
}
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
booksPerRow = 8.0;
}
//calculate right height do display all cells
NSInteger cvHeight = (ceil((float)[allBooksCollectionView numberOfItemsInSection:0]/booksPerRow)*200.0)+49.0;
return cvHeight;
}
-(void)allBooksCollectionViewSetConstraints
{
NSInteger cvHeight = [self allBooksCollectionViewHeight];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view(%d)]", cvHeight] options:0 metrics:nil views:@{@"view":allBooksCollectionView}]];
}
我已经尝试从 UIScrollview 中移除 UICollectionView 约束,但它并没有改变任何东西。
[scrollView removeConstraints:allBooksCollectionView.constraints];
在方向更改时,我收到以下错误:
Unable to simultaniously satisfy constraints ... (
"<NSLayoutConstraint:0x9aa49f0 V:[UICollectionView:0xc0b6000(849)]>",
"<NSLayoutConstraint:0xb2b15d0 V:[UICollectionView:0xc0b6000(1049)]>"
)
Will attempt to recover by breaking constraint <NSLayoutConstraint:0xb2b15d0 V:[UICollectionView:0xc0b6000(1049)]>
但是另一个约束需要被打破!不是这个,因为 1049 是 cvHeight。
我该如何解决这个问题?
【问题讨论】:
-
您应该只在 updateConstraints 或 updateViewConstraints 中添加约束
标签: ios uiscrollview uicollectionview autolayout nslayoutconstraint