首页 > 解决方案 > 如何实现折叠标题?

问题描述

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

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
}

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

标签: iosswiftuiscrollviewuiscrollviewdelegate

解决方案


这是处理headerView heightwith 的方法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中,

  1. 崩溃tableView_scrolled up
  2. tableView是时展开scrolled down

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


推荐阅读