iosswiftuiviewpropertyanimator

UIViewPropertyAnimator doesn’t work as expected


I am trying to animate a UIView and an imageView when the user taps on the UIView. here is my code:

// When the user taps on the featured story image view
@objc func feturedStoryTapped() {

    /*featuredStoryView.layer.zPosition = 1

    // Hide the necessary elements
    self.featuredTitle.isHidden = true
    self.bookTitle.isHidden = true
    self.authorName.isHidden = true

    // Unhide the necessary elements
    self.exitButton.isHidden = false*/

    let animator = UIViewPropertyAnimator(duration: 0.9, dampingRatio: 0.4, animations: {

        self.featuredStoryView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
        self.bookCover.frame = CGRect(x: 100, y: 75, width: 250, height: 280)

    })

    animator.startAnimation()

}

Expected behaviour: When I tap on the UIView once, the view should take up the whole screen and the imageView should shrink a little.

Problem The problem is that when I tap on the view once, the view takes up the whole screen but the imageView doesn't shrink, it only shrinks when I tap for the second time.

I want both the tasks to execute when I tap on the view once. I will add a GIF to aid understanding.

GIF


Solution

  • Fiexd it, just add view.layoutIfNeeded() between the two lines of code inside the property animator.

    // When the user taps on the featured story image view
        @objc func feturedStoryTapped() {
    
        /*featuredStoryView.layer.zPosition = 1
    
        // Hide the necessary elements
        self.featuredTitle.isHidden = true
        self.bookTitle.isHidden = true
        self.authorName.isHidden = true
    
        // Unhide the necessary elements
        self.exitButton.isHidden = false*/
    
        let animator = UIViewPropertyAnimator(duration: 0.9, dampingRatio: 0.4, animations: {
    
            self.featuredStoryView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
            Self.view.layoutIfNeeded()
    
            self.bookCover.frame = CGRect(x: 100, y: 75, width: 250, height: 280)
    
        })
    
        animator.startAnimation()
    
    }