Search code examples
swiftanimationuicollectionviewautolayoutnslayoutconstraint

How do you animate a UICollectionView using auto layout anchors?


I'm trying to animate a collectionview by using layout constraints however I cannot get it to work. I have a collectionview that takes up the entire screen and on a button tap I want to essentially move the collectionview up to make room for another view to come in from the bottom - see image below

The incoming UIView animates just fine (the view coming up from the bottom) - The reason I want to move the collectionview is that the incoming UIView obscures the collection view so am just trying to move the collectionview up at the same time as the new view so that all of the content in the collectionview can be displayed without being hidden by the new view - I use a reference view to get the right layout constraints for the final position for the collectionview Image to show what I am trying to achieve Am I going about it the right way?

Nothing happens with the code example below and I am not sure where to go from here - the same approach is used for animating the incoming view and works just fine but doesn't seem to work for the collectionview...

Any help would be kindly appreciated

 var colViewBottomToReferenceTop: NSLayoutConstraint?
 var colViewBottomToViewBottom: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()

     colViewBottomToReferenceTop = musicCollectionView.bottomAnchor.constraint(equalTo: referenceView.topAnchor)   
     colViewBottomToViewBottom = musicCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)

     NSLayoutConstraint.active([colViewBottomToViewBottom!])
     NSLayoutConstraint.deactivate([colViewBottomToReferenceTop!]) 

}

func playerShow() {
    NSLayoutConstraint.activate([colViewBottomToReferenceTop!])
  UIView.animate(withDuration: 0.5, animations: {
        self.view.layoutIfNeeded()
    })
}


@IBAction func btnTapped(_ sender: UIButton) {
    playerShow()
   }

Solution

  • You want to deactivate the other before animation

    NSLayoutConstraint.deactivate([colViewBottomToViewBottom!]) 
    NSLayoutConstraint.activate([colViewBottomToReferenceTop!])
    

    Look to this Demo