VideoPlayer 视图防止 SwiftUI 导航栏隐藏

问题描述

当我将 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())
    }
  }
}

解决方法

我遇到了同样的问题。不确定是什么原因造成的,但我最终用自定义的替换了 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>")