我试图这样隐藏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更好?
答案 0 :(得分:9)
通过将这些更改放置在动画块中,可以为更改后的子视图的isHidden属性和堆栈视图的属性设置动画。
我已经使用iOS 12.1模拟器测试了以下代码,并且可以正常工作。
UIView.animate(
withDuration: 2.0,
delay: 0.0,
options: [.curveEaseOut],
animations: {
self.label.isHidden = true
self.label.alpha = 0.0
})
答案 1 :(得分:3)
您可以为视图属性设置动画,例如alpha
,color
等。但是,有些事情会立即发生-在这种情况下为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
}
答案 2 :(得分: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()
}
}
答案 3 :(得分: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()
}
答案 4 :(得分:0)
只需将简单的解决方案与animateKeyframes
一起使用,以淡化alpha,然后隐藏即可,我想这将为您提供所需的内容,所以在1秒和0.8秒褪色后隐藏
// showLabel是Bool来处理状态,请在您的File中声明它
@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
}
})
}