当用户在表视图中滚动时,动画显示约束的变化



我有一个视图,它充当另外两个视图的容器(一个视图占据屏幕的1/4,一个表视图占屏幕的3/4)。我想要的是,当用户向上滚动(滑动方向)表格视图时,表格视图将平滑地向上滚动到屏幕上,当用户向下滚动时向下滚动(滑动)。

到目前为止,我已经设法使表视图上升,但它做得太突然,无法使其下降。以下是我的操作方法:viewViewTopConstraint是容器顶部约束的表视图顶部约束

extension StatsOverlayViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == statsTableView {
let scrolledOffset = scrollView.contentOffset.y
while viewViewTopConstraint.constant > 0  && viewViewTopConstraint.constant < 69 {
print("scrolling with offset(scrollView.contentOffset.y)")
self.viewViewTopConstraint.constant -= scrolledOffset
}
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == statsTableView {
if  viewViewTopConstraint.constant < 0 {
viewViewTopConstraint.constant = 0
} else if viewViewTopConstraint.constant > 69 {
viewViewTopConstraint.constant = 69
}
}
}

}

编辑:

放回视图的问题是由于滚动视图.bozens=true和while循环的错误使用有效的代码是:

func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == statsTableView {
let scrolledOffset = scrollView.contentOffset.y
UIView.animateWithDuration(0.2, animations: {
if scrolledOffset > 0 {
self.viewViewTopConstraint.constant = 0
} else {
self.viewViewTopConstraint.constant = self.viewViewTopConstraintOriginalValues
}
self.view.layoutIfNeeded()
})
}
}

您需要在UIView.animate块中调用self.view.layoutIfNeeded

UIView.animate(withDuration: 1) { 
self.view.layoutIfNeeded
}

在更改约束后立即添加此代码。如果你想对你的动画有更多的控制,可以使用这个

UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseInOut], animations: {
self.view.layoutIfNeeded
}, completion: nil)