SwiftUI-更新父视图状态时如何保留子视图状态?

时间:2020-06-30 12:57:10

标签: ios swift xcode swiftui avplayer

我正在尝试找到一种在父级更新时保留子级视图的方法。我有以下设置:

struct VideoPlayerView: View {
       
    @State var fullScreen : Bool = false
    
    var body: some View {
        NavigationView {
            VStack {                
                PlayerContainerView(url: URL(string: "video-link-from-vimeo")!, fullScreen: $fullScreen)
                
                if !fullScreen {                    
                    VStack {
                        ...very long content here...
                    }                          
                }
            }
            .backgroundColor(self.fullScreen ? K.Colors.AppText : K.Colors.AppBackground)
            .hideNavigationBar()
        }
        .hideNavigationBar()
    }
}

PlayerContainerView只是我的包装,其中包含AVPlayer和一些自定义控件。首先,如果要显示播放器,我正在使用Section 5. of this official SwiftUI Tutorial中的这项技术。

我正在加载的视频来自Vimeo。 fullScreen @State属性正在从子视图中更新。

想要的结果

我希望能够隐藏播放器下的所有内容,以便播放器全屏显示。这可能会在任何时间发生-例如,当视频已经播放时,视频在特定时间暂停时等。

问题

问题是,如果我更新fullScreen @State属性,则会获得全新的View,实际上,如果我在进入全屏模式之前播放视频,我会听到它仍在后台播放。我的全屏视频现在从头开始,而不是从进入全屏之前的位置恢复。

1 个答案:

答案 0 :(得分:4)

问题是在视图更新之间未还原AVPlayer的状态。一种可能的解决方案是将AVPlayer作为参数提供给PlayerContainerView(而不是URL)。

相关问题