【问题标题】:VideoPlayer view prevents SwiftUI Navigation Bar from hidingVideoPlayer 视图防止 SwiftUI 导航栏隐藏
【发布时间】:2021-06-28 00:40:01
【问题描述】:

当我将VideoPlayer 视图放在NavigationView 的父视图或子视图中时,就会出现问题。在本例中,子视图将显示导航栏:

struct ParentView: View {
  var body: some View {
    NavigationView {
      VStack {
        Text("Parent View")

        NavigationLink(destination: ChildView().navigationBarHidden(true)) {
          Text("Child View")
        }
      }
      .navigationBarHidden(true)
    }
  }
}

struct ChildView: View {
  var body: some View {
    VStack {
      Text("Child View")
      VideoPlayer(player: AVPlayer())
    }
  }
}

【问题讨论】:

    标签: swiftui navigationbar navigationview swiftui-navigationlink avkit


    【解决方案1】:

    我遇到了同样的问题。不知道是什么原因造成的,但我最终用自定义替换了VideoPlayer。这删除了顶部的空间。

      struct CustomPlayer: UIViewControllerRepresentable {
      let src: String
    
      func makeUIViewController(context: UIViewControllerRepresentableContext<CustomPlayer>) -> AVPlayerViewController {
        let controller = AVPlayerViewController()
        let player = AVPlayer(url: URL(string: src)!)
        controller.player = player
        player.play()
        return controller
      }
    
      func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<CustomPlayer>) { }
    }
    

    在你想使用它的地方,做:

    CustomPlayer(src: "<the source to the video>")
    

    【讨论】:

    • 谢谢!此解决方案有效。但是我在使用 CustomPlayer 时遇到了另一个问题——它不适用于动态源。我尝试通过 AVPlayer 而不是 src,但仍在寻找解决方案以使其在更改时更新源。
    【解决方案2】:

    如果您想要一个自定义播放器,其初始化程序与本机播放器相同,并且会随着应用程序的当前状态而更新:

    struct CustomPlayer: UIViewControllerRepresentable {
        let player: AVPlayer
    
        func makeUIViewController(context: UIViewControllerRepresentableContext<CustomPlayer>) -> AVPlayerViewController {
            let controller = AVPlayerViewController()
            controller.player = player
            return controller
        }
    
        func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<CustomPlayer>) {
            uiViewController.player = player
        }
    }
    
    

    请注意,在 updateUIViewController(_: context:) 上,您应该使用您声明并希望更新的每个变量来更新视图

    【讨论】: