如何实现折叠标头?



我试图实现一个折叠的UITableView Header,但现在我没有进一步。这是我的故事板。我尝试使用scrollViewDidScroll(scrollView:UIScrollView)委托方法,但是在嵌入在容器中的表视图中滚动时,位置根本没有变化。高度约束是我的容器标题视图的高度。 这是我的类的完整源代码。我感谢任何帮助!在这个问题上坐了一段时间了。

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.heightConstraint.constant = self.maxHeaderHeight
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let absoluteTop: CGFloat = 0
let absoluteBottom: CGFloat = scrollView.contentSize.height - scrollView.frame.size.height
let scrollDiff = scrollView.contentOffset.y - self.previousScrollOffset
let isScrollingDown = scrollDiff > 0 && scrollView.contentOffset.y > absoluteTop
let isScrollingUp = scrollDiff < 0 && scrollView.contentOffset.y < absoluteBottom
var newHeight = self.heightConstraint.constant
if isScrollingDown {
newHeight = max(self.minHeaderHeight, self.heightConstraint.constant - abs(scrollDiff))
} else if isScrollingUp {
newHeight = min(self.maxHeaderHeight, self.heightConstraint.constant + abs(scrollDiff))
}
if newHeight != self.heightConstraint.constant {
self.heightConstraint.constant = newHeight
}
self.previousScrollOffset = scrollView.contentOffset.y
}

向上滚动时,标题容器应消失/更改其位置。

以下是使用tableViewscrolling处理headerViewheight的方法,

class VC: UIViewController {
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
var lastContentOffset: CGFloat = 0.0
let maxHeaderHeight: CGFloat = 115.0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
//Scrolled to bottom
UIView.animate(withDuration: 0.3) {
self.heightConstraint.constant = 0.0
self.view.layoutIfNeeded()
}
}
else if (scrollView.contentOffset.y < self.lastContentOffset || scrollView.contentOffset.y <= 0) && (self.heightConstraint.constant != self.maxHeaderHeight)  {
//Scrolling up, scrolled to top
UIView.animate(withDuration: 0.3) {
self.heightConstraint.constant = self.maxHeaderHeight
self.view.layoutIfNeeded()
}
}
else if (scrollView.contentOffset.y > self.lastContentOffset) && self.heightConstraint.constant != 0.0 {
//Scrolling down
UIView.animate(withDuration: 0.3) {
self.heightConstraint.constant = 0.0
self.view.layoutIfNeeded()
}
}
self.lastContentOffset = scrollView.contentOffset.y
}
}

在上面的代码中,headerView将,

  1. scrolled uptableView崩溃
  2. tableViewscrolled down展开

如果您仍然遇到任何问题,请告诉我。

最新更新