我想在navigationItem.titleView
下实现一个折叠视图,其中带有一个搜索栏,每当用户在tableView中向上/向下滚动时,该折叠视图就会折叠。我想我必须以编程方式添加一个UIView()
并将其放置在我的UITableView()
和navigationItem.titleView之间,但是我在实现时遇到了一些问题并限制了UIView()
。
如果有人可以帮我解决这个问题,那就太好了。
我找到了下面的代码,但是我不确定它是否对我有帮助。
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
}
}
UIView()
应该在用户向下滚动时显示,并在用户向上滚动时折叠。