Search code examples
iosswift3autolayoutios-animations

Auto-Layout animation takes center as anchoring point


I have an height animation based on constraints. However when animation starts it takes view's center as anchoring point not the top.

I want it to animate as fixed top and shrinking from the bottom.

Sorry for my English not a native speaker.

my views anchors:

top: superview
left: superview
right: superview
bottom: nil

// current height constant 200
view.height.constant = 0

UIView.animation(withDuration: 0.2, animations: {
    view.layoutIfNeded()
}}

Solution

  • Try instead of your view:

    superView.layoutIfNeeded()
    

    this will layout the subview and your animation should work.

    so replace

        // current height constant 200
    view.height.constant = 0
    
    UIView.animation(withDuration: 0.2, animations: {
        view.layoutIfNeded()
    }
    

    with

        // current height constant 200
    yourView.height.constant = 0
    
    UIView.animation(withDuration: 0.2, animations: {
        yourViewSuperview.layoutIfNeded()
    }
    

    see layoutIfNeeded() apple docs: [1]https://developer.apple.com/documentation/uikit/uiview/1622507-layoutifneeded