如何在SwiftUI中像Facebook一样,向上滑动时隐藏导航栏,向下滑动时显示?在UIKit中,有navigationBar.hideBarsOnSwipe
,但我似乎在SwiftUI中找不到这样的功能。我是漏掉了什么,还是SwiftUI确实没有滑动隐藏的功能?
提前致谢!
目前 SwiftUI(包括 1.0 和 2.0 版本)中没有原生的 API。因此,这里提供了一个可能可行的解决方案,基于在这个答案中提供的 NavigationConfigurator
。
已在 Xcode 12 / iOS 14 上测试通过。
更新:已在 Xcode 13.4 / iOS 15.5 上重新测试,仍然可以正常工作!
struct TestHideOnSwipe: View {
var body: some View {
NavigationView {
List(0..<100) { i in
Text("Item \(i)")
}
.background(NavigationConfigurator { navigationConfigurator in
navigationConfigurator.hidesBarsOnSwipe = true // << here !!
})
.navigationBarTitle(Text("Demo"), displayMode: .inline)
}
}
}
extension View {
func navigationBarsHideOnSwipe(_ hidesBarsOnSwipe: Bool) -> some View {
self.background(NavigationConfigurator { $0.hidesBarsOnSwipe = hidesBarsOnSwipe })
}
}
- Natanel您可以在导航控制器的属性检查器中获取此属性。
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if(velocity.y>0) {
//Code will work without the animation block.I am using animation block incase if you want to set any delay to it.
UIView.animate(withDuration: 2.5, delay: 0, options: UIViewAnimationOptions(), animations: {
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.navigationController?.setToolbarHidden(true, animated: true)
print("Hide")
}, completion: nil)
} else {
UIView.animate(withDuration: 2.5, delay: 0, options: UIViewAnimationOptions(), animations: {
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.setToolbarHidden(false, animated: true)
print("Unhide")
}, completion: nil)
}
}
如果你想以编程的方式实现它。 注意:如果你要从这个视图控制器传递任何数据到另一个嵌入了导航控制器的视图控制器,你可能需要取消隐藏NavigationBar。