Search code examples
iosswiftuiviewanimation

How to animate a UIView partially offscreen


I have a rectangle UIView that sits at the bottom of its parent view (which is the full height and width of the screen) that I would like to animate down partially off of the screen after responding to an event. I have tried the following, but it just moves the origin up 100 and animates back to where it started:

UIView.animate(withDuration: 1.0, 
               delay: 1.2, 
               options: .curveEaseIn, 
               animations: {
                    self.subview.frame.origin.y += 100
                }, completion: {})

I've also tried setting a top constraint and changing that, but then it just squishes the view and it's children.


Solution

  • This are the outlets

        @IBOutlet weak var topConstraint: NSLayoutConstraint!
        @IBOutlet weak var testview: UIView!
    

    Add this animation block where you want to animate on button action or user interaction.

    self.topConstraint.constant += 100
        UIView.animate(withDuration: 5.0,
                       delay: 10,
                       options: .curveEaseIn,
                       animations: {
                        self.testview.layoutIfNeeded()
        }, completion: nil)
    

    enter image description here

    enter image description here