【发布时间】:2018-07-05 02:23:08
【问题描述】:
我想在 collectionview 的顶部创建一个菜单栏。当用户向下滚动时,菜单栏会逐渐隐藏,而当用户向上滚动时,菜单栏会立即出现。该行为类似于导航栏的 hidewhenswipe 功能。这是在此菜单栏上创建此类行为的任何解决方案吗?谢谢。
[截图]
【问题讨论】:
标签: ios swift uiviewcontroller uicollectionview
我想在 collectionview 的顶部创建一个菜单栏。当用户向下滚动时,菜单栏会逐渐隐藏,而当用户向上滚动时,菜单栏会立即出现。该行为类似于导航栏的 hidewhenswipe 功能。这是在此菜单栏上创建此类行为的任何解决方案吗?谢谢。
[截图]
【问题讨论】:
标签: ios swift uiviewcontroller uicollectionview
如果还没有给你的标题视图一个高度限制。然后连接该约束,例如
@IBOutlet 弱变量 headerViewHeightConstraint: NSLayoutConstraint!
确认您的 ViewController 为 UICollectionViewDelegate 和 UIScrollViewDelegate
在 ViewDidLoad() 中设置 collectionView.delegate = self
UICollectionView 是 UIScrollView 的子类,因此您可以重写 scrollViewDidScroll 的委托方法并使用以下代码
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > 50 {// the value when you want the headerview to hide
view.layoutIfNeeded()
headerViewHeightConstraint.constant = 0
UIView.animate(withDuration: 0.5, delay: 0, options: [.allowUserInteraction], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}else {
// expand the header
view.layoutIfNeeded()
headerViewHeightConstraint.constant = 100 // Your initial height of header view
UIView.animate(withDuration: 0.5, delay: 0, options: [.allowUserInteraction], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
【讨论】:
我一直在使用 HidingNavigationBarManager 来做你刚才描述的事情 它非常易于使用。如果您的 ViewController 中有一个 tableView,那么 就像将这些行添加到您的代码中一样简单。
var hidingNavBarManager: HidingNavigationBarManager?
...
...
override func viewDidLoad() {
super.viewDidLoad()
self.hidingNavBarManager = HidingNavigationBarManager(viewController: self, scrollView: tableView)
}
【讨论】: