Search code examples
swiftuiswipegesturerecognizer

How to add slide animation to uiview height constant?


I'm trying to create the effect that when scroll/swipe down, the UIView on the top of the view controller will shrink and the bottom part will expand.

Here's my code for the swipe gesture I added to the upper view.

@IBAction func swipeUp(_ sender: UISwipeGestureRecognizer) {
        if(upperView.isHidden == false){
            upperView.isHidden = true
            self.heightUpperView.constant = 0
            self.view.layoutIfNeeded()
        }
        else{
            self.heightUpperView.constant  = 372
            upperView.isHidden = false
            self.view.layoutIfNeeded()
        }
    }

It works but there's lack of animation. I wonder what would be the best approach to mimic the scrolling animation or sticky header animation.

Thank you for your help in advance.


Solution

  • self.view.layoutIfNeeded() must be called from UIView.animateWith.... Here is an example with your code:

    @IBAction func swipeUp(_ sender: UISwipeGestureRecognizer) 
    {
         // Set new constants first
         if(upperView.isHidden == false)
         {
              upperView.isHidden = true
              self.heightUpperView.constant = 0
         }
         else
         {
              self.heightUpperView.constant  = 372
              upperView.isHidden = false
         }
    
         // This line will animate all your constraint changes
         UIView.animate(withDuration: 0.3) 
         {
              self.view.layoutIfNeeded()
         }
    }