如何实现折叠标头?

时间:2019-06-12 07:47:15

标签: ios swift uiscrollview uiscrollviewdelegate

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

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
}

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

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式使用headerView height处理tableView scrolling

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中,

    tableViewscrolled up
  1. 折叠
  2. tableViewscrolled down
  3. 展开

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