Akeno Akeno - 4 months ago 21
iOS Question

Animate constraints of a UIView (as subview of the main view)

I set the constraints of the view I dragged on to the storyboard so that the view reaches over the whole screen. (I pinned it 0 from the top, left, bottom and right). When the view appears I want the view to shrink. The constant should animate from 0 to 20.

In the app, it changes the constant, but it does not animate it. Also, behind that shrunk view, everything is black although it should be white (because behind that view is the main view which is white).

override func viewDidAppear(animated: Bool) {

UIView.animateWithDuration(2.5, animations: {
self.leftPin.constant = 20.0
self.topPin.constant = 20.0
self.rightPin.constant = 20.0
self.bottomPin.constant = 20.0
// bg is my view I want to shrink
self.bg.layoutIfNeeded()
})
}


I read that in order to "apply" new constraints to the actual layout, You have to run layoutIfNeeded(). But those constraints above also work without that function. Why?

Answer

@try this

override func viewDidAppear(animated: Bool) {

    self.leftPin.constant = 20.0
    self.topPin.constant = 20.0
    self.rightPin.constant = 20.0
    self.bottomPin.constant = 20.0

    UIView.animateWithDuration(2.5, animations: {

    self.view.layoutIfNeeded()
    })
}