繁体   English   中英

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

[英]UIStackView - hide and collapse subview with animation

我试图像这样隐藏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可能会更好?

根据Apple的文档

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

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

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

安排的子视图动画Gif

您可以为视图属性设置动画,例如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
}

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

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

动画

确保你没有给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()
}

只是你可以使用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
        }

    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM