Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIStackView - hide and collapse subview with animation

I'm trying to hide UIStackView's subview like this:

UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 2.0, 
      delay: 0, options: [.curveEaseOut], animations: {
    self.label.isHidden = true
    self.label.alpha = 0.0
    self.stackView.layoutIfNeeded()
})

However, the label disappears instantly with using this code. I suspect this is because of setting isHidden to true, which is required for collapsing.

Is there a way how to hide and collapse UIStackView's subvew with animation? Or it might be better to not to use UIStackView at all?

like image 848
Andrey Gordeev Avatar asked Jan 05 '19 18:01

Andrey Gordeev


People also ask

What is Stackview alignment?

A layout where the stack view aligns the center of its arranged views with its center along its axis. case leading. A layout for vertical stacks where the stack view aligns the leading edge of its arranged views along its leading edge.

What is Uistackview?

A streamlined interface for laying out a collection of views in either a column or a row.


2 Answers

According to Apple's documentation:

You can animate both changes to the arranged subview’s isHidden property and changes to the stack view’s properties by placing these changes inside an animation block.

I've tested the below code using iOS 12.1 Simulator and it works as expected.

UIView.animate(
    withDuration: 2.0,
    delay: 0.0,
    options: [.curveEaseOut],
    animations: {
        self.label.isHidden = true
        self.label.alpha = 0.0
})

Arranged Subview Animation Gif

like image 150
Wez Avatar answered Sep 27 '22 18:09

Wez


You can animate view properties like alpha, color, etc. However, some things happen instantly - isHidden in this case.

Here's an example using UIView.animate:

UIView.animate(withDuration: 2, delay: 0, options: .curveEaseOut, animations: {
    self.label.alpha = 0 // Changes the label's layer alpha value
}, completion: { finished in
    self.label.isHidden = true // Hides the label
    self.label.layer.alpha = 1 // Resets the label's alpha without un-hiding it
})

Using UIViewPropertyAnimator:

UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 2, delay: 0, options: .curveEaseOut, animations: {
    self.label.alpha = 0 // Sets the label's alpha
}) { _ in
    self.label.isHidden = true // Hides the label
    self.label.alpha = 1 // Resets the label's alpha without un-hiding it
}
like image 40
ZGski Avatar answered Sep 27 '22 19:09

ZGski