UIStackView - 使用动画隐藏和折叠子视图

问题描述 投票:4回答:5

我试图像这样隐藏UIStackView的子视图:

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

但是,使用此代码时标签会立即消失。我怀疑这是因为将isHidden设置为true,这是折叠所必需的。

有没有办法如何隐藏和折叠UIStackView的动画子菜单?或者根本不使用UIStackView可能会更好?

ios swift uistackview
5个回答
9
投票

Apple's documentation说:

您可以对已排列的子视图的isHidden属性进行两个更改的动画处理,并通过将这些更改放在动画块中来更改堆栈视图的属性。

我已经使用iOS 12.1模拟器测试了以下代码,它按预期工作。

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

Arranged Subview Animation Gif


3
投票

您可以为alphacolor等视图属性设置动画。但是,有些事情会立即发生 - 在这种情况下是isHidden

这是使用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
})

使用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
}

1
投票

我试过你的代码。它的动画

if self.stackView.subviews.count > 0 {
            UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1.0, delay: 0, options: [.curveEaseOut], animations: {

                self.stackView.subviews[0].isHidden = true
                self.stackView.subviews[0].alpha = 0.0
                self.stackView.layoutIfNeeded()
            }) { (position) in
                self.stackView.subviews[0].removeFromSuperview()
            }
        }

initialScreen

animated


0
投票

确保你没有给stackview赋予高度约束。试试这个。

UIView.animate(withDuration: 0.5) {
   self.stackView.subviews[INDEX_OF_LABEL_IN_STACK]?.alpha = 0
   self.stackView.subviews[INDEX_OF_LABEL_IN_STACK]?.isHidden = true
   self.view.layoutSubviews()
}

0
投票

只是你可以用animateKeyframes的简单解决方案淡化alpha,然后隐藏,我想这会给你你需要的东西所以隐藏1秒和0.8秒后褪色

// showLabel是Bool来处理状态声明它在你的文件

@IBAction func toggleStackLabelTapped(_ sender: UIButton) {

    showLabel = !showLabel

    UIView.animateKeyframes(withDuration: 1, delay: 0, options: .calculationModeLinear, animations: {
        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.8) {
            self.label.alpha =  (self.showLabel) ? 1 : 0
        }
        UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 1) {
            self.label.isHidden = !self.showLabel
        }

    })
}
© www.soinside.com 2019 - 2024. All rights reserved.