视频播放器视图可防止 SwiftUI 导航栏隐藏



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

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

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

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:)上,您应该使用您声明的每个变量更新视图并期望更新

相关内容

  • 没有找到相关文章

最新更新