Changing the position of the autolayout enabled co

2019-08-20 05:33发布

问题:

A part of my application is showing a list in UIcollectionView, if the user swipe down the screen I will present the UISearchBar with animation from the top of the viewController. I did all of them in a separate viewController.

I use autolayout to position the controls in that viewController.

I move the search bar form y=-88 to y=0 and move the collectionView down to make space for searchBar with animation when the user swipe down the screen, my problem is that if I make call to reloadData to collectionView, both search bar and CollectionView move to their previous autolayouted positions

I use below animation to move them

[UIView animateWithDuration:0.4 animations:^(void){
        fileSearchBar.frame=fileSearchBar.frame=CGRectOffset(fileSearchBar.frame, 0,88);
        chartsCollectionView.frame=gridFrame;///gridFrame is calculated to move down
    }]; 

I there a way to stop them moving to their pre-calculated position

回答1:

When you use auto layout, you must not set frames. You have to change constraints and let that change the frames indirectly.

Apple's Auto Layout Guide shows an example of animating:

[containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
[UIView animateWithDuration:0.4 animations:^{
     // Make all constraint changes here
     [containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
}];

You don't show how you set up your constraints, so I can't show you how to modify them to move the search bar and collection view. Ideally, you'd just need to set the constant property of one of the constraints. (Your constraints should be set up so that moving one thing causes the other to adjust itself automatically.)