Hide navigation bar on swipe of a list in SwiftUI

点点圈 提交于 2021-01-23 06:49:25

问题


How to to hide the navigation bar when swiping up and to show when swiping down (like on facebook for example) in SwiftUI? In UKit there is navigationBar.hideBarsOnSwipe, but I do cannot seem to find such functionality in SwiftUI. Am I missing something, or there is indeed no hide on swipe in swiftUI?

Thanks in advance!!


回答1:


No native API in SwiftUI so far (both 1.0 & 2.0). So here is a possible working solution based on NavigationConfigurator provided in this answer

Tested with Xcode 12 / iOS 14

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



回答2:


you can get this attribute in navigation controller's attributes inspector.

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

}

if you want to do it programmatically. Note: If you passing any data from this VC to another VC that embedded with navigationController.You may need to unhide the NavigationBar.



来源:https://stackoverflow.com/questions/61324597/hide-navigation-bar-on-swipe-of-a-list-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!