Autolayout约束:无法同时满足约束

时间:2013-12-18 10:43:42

标签: ios uiscrollview uicollectionview autolayout nslayoutconstraint

我在添加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。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

  

我尝试从UIScrollview中删除UICollectionView约束,但它不会改变任何东西。

[scrollView removeConstraints:allBooksCollectionView.constraints];

这行代码错了。从collectionView.constraints返回的约束都不在滚动视图上,因此此调用将不执行任何操作。您应该将您关心的约束存储在属性或实例变量中:

if (collectionViewHeightConstraints)
{
    [scrollView removeConstraints:collectionViewHeightConstraints];
}
collectionViewHeightConstraints = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view(%d)]", cvHeight] options:0 metrics:nil views:@{@"view":allBooksCollectionView}];
[scrollView addConstraints:collectionViewHeightConstraints];
相关问题