首页 > 解决方案 > 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())
    }
  }
}

标签: swiftuinavigationbarnavigationviewswiftui-navigationlinkavkit

解决方案


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

推荐阅读