我已经编写了此代码来更改视图高度的约束,但它不起作用。这会在没有动画的情况下更改我的视图高度并立即更改它。
//MARK:Scrollview delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > 0 {
self.topView.layoutIfNeeded()
UIView.animate(withDuration: 3.0, animations: {
self.topViewHeight.constant = 64
self.topView.layoutIfNeeded()
})
}
}
需要在UIView.animate
之外设置新的约束常量,还要调用setNeedsLayout()
。此外,我猜你只想在开始时调用一次该动画,这样你就可以实现一个简单的保护来测试它是否已经被扩展(或折叠,取决于你试图做什么(。
var isTopViewCollapsed = false
//MARK:Scrollview delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > 0 && !isTopViewCollapsed {
isTopViewCollapsed = true
self.topView.superview?.layoutIfNeeded()
self.topViewHeight.constant = 64
// you need to tell the autolayout that constraints been changed
self.topView.superview?.setNeedsLayout()
UIView.animate(withDuration: 3.0, animations: {
self.topView.superview?.layoutIfNeeded()
})
}
}