在SwiftUI中,如何在滑动列表时隐藏导航栏

3

如何在SwiftUI中像Facebook一样,向上滑动时隐藏导航栏,向下滑动时显示?在UIKit中,有navigationBar.hideBarsOnSwipe,但我似乎在SwiftUI中找不到这样的功能。我是漏掉了什么,还是SwiftUI确实没有滑动隐藏的功能?

提前致谢!


SwiftUI仍然非常年轻,许多功能尚未得到支持。我在Apple的文档中找不到任何相关信息。也许与UIKit集成将是一个可接受的选择。 - xiaoyu2006
2个回答

3

目前 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)
        }
    }
}

Test module on GitHub


1
有用的扩展:extension View { func navigationBarsHideOnSwipe(_ hidesBarsOnSwipe: Bool) -> some View { self.background(NavigationConfigurator { $0.hidesBarsOnSwipe = hidesBarsOnSwipe }) } } - Natanel
1
它可以正确地隐藏它,但无法再次显示它 :( - Arslan Asim

-3

click on the highlighted checkbox

您可以在导航控制器的属性检查器中获取此属性。

  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。


3
嘿!谢谢回答!但是我问的是如何在SwiftUI中实现,而不是使用UIKit :/ - Danny Richard Aboo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接