【问题标题】:Hide navigation bar on swipe of a list in SwiftUI在 SwiftUI 中滑动列表时隐藏导航栏
【发布时间】:2020-04-20 14:13:09
【问题描述】:

如何在 SwiftUI 中向上滑动时隐藏导航栏并在向下滑动时显示(例如在 facebook 上)?在 UKit 中有 navigationBar.hideBarsOnSwipe,但我似乎在 SwiftUI 中找不到这样的功能。我是否遗漏了什么,或者 swiftUI 中的滑动确实没有隐藏?

提前致谢!!

【问题讨论】:

  • SwiftUI 那时还很年轻,很多功能还不支持。我在Apple's documentation 中找不到与此相关的任何内容。也许与 UIKit 集成将是一个可以接受的选择。

标签: ios swift xcode swiftui


【解决方案1】:

到目前为止,SwiftUI 中没有原生 API(1.0 和 2.0)。所以这是一个可能的工作解决方案,基于this answer中提供的NavigationConfigurator

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

【讨论】:

  • 有用的扩展:extension View { func navigationBarsHideOnSwipe(_ hidesBarsOnSwipe: Bool) -&gt; some View { self.background(NavigationConfigurator { $0.hidesBarsOnSwipe = hidesBarsOnSwipe }) } }
  • 它确实隐藏了它,但不再显示它:(
【解决方案2】:

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

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

}

如果您想以编程方式进行。 注意:如果您将任何数据从这个 VC 传递到另一个嵌入了 navigationController 的 VC。您可能需要取消隐藏 NavigationBar。

【讨论】:

  • 嘿!感谢您的回答!但是我问如何在 SwiftUI 中做到这一点,而不是使用 UIKit :/
猜你喜欢
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多