Search code examples
iosswiftanimationsubviewstackview

Swift StackView interchange subview with animation


How do I make subviews of stack interchange with animation

UIView.animateWithDuration(0.5, animations:
{
    self.stackview.exchangeSubviewAtIndex(3, withSubviewAtIndex: 4)
})

This works when views are not in stack view :

let lastXcoVar = lastView.center.x 

UIView.animateWithDuration(0.5, animations:
{
    lastView.center.x = nextView.center.x
    nextView.center.x = lastXcoVar
})

Solution

  • Animation is just a visualization. You can do the same animation as your views not in stack view, after the animation is finished we use exchangeSubviewAtIndex to update the views on stack view. For example:

    let lastXcoVar = lastView.center.x
    
    UIView.animateWithDuration(0.5, animations:
    {
        lastView.center.x = nextView.center.x
        nextView.center.x = lastXcoVar
    }) { _ in
        self.stackview.exchangeSubviewAtIndex(<index of lastView>, withSubviewAtIndex: <index of nextView>)
    }