I have an issue with adding a NSLayoutConstraint. I'd like to update the height of an UICollectionView so that all cells fit in the UICollectionView without scrolling. This is because I have put the UICollectionView in a UIScrollView, together with other UI Elements.
I have set the constraints in the interface builder, and I resize the UICollectionView on viewDidLoad, when I know how many items should be displayed. I do this with
[self allBooksCollectionViewSetConstraints];
I have set
[allBooksCollectionView setTranslatesAutoresizingMaskIntoConstraints:NO];
This is my code
- (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}]];
}
I have tried removing the UICollectionView constraints from the UIScrollview, but it doesn't change a thing.
[scrollView removeConstraints:allBooksCollectionView.constraints];
On orientation change I get the following error:
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)]>
But the other constraint needs to be broken! Not this one, because 1049 is cvHeight.
How can I fix this?