简体   繁体   中英

SwiftUI - How to preserve child view's state when updating parent view's state?

I am trying to find a way to preserve the child view when the parent gets updated. I have the following setup:

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 is just my wrapper holding the AVPlayer and some custom controls. To display the player in the first place I am using this technique from Section 5. of this official SwiftUI Tutorial if that's relevant.

The video I am loading is from Vimeo. The fullScreen @State property is getting updated from the child view.

Wanted Result

I would like to be able to hide everything that's under my player so that the player is then displayed on full screen. This could happen at any time - ie when the video is already playing, when the video is paused at specific time etc.

The Issue

The issue is that if I update that the fullScreen @State property I get whole new View and actually if I was playing the video before entering full screen I am hearing it still play in the background. My full screen video is now starting from the beginning and not resuming from where it was before entering full screen.

The issue is that the state of AVPlayer is not restored between View updates. A possible solution is to provide the AVPlayer as a parameter to your PlayerContainerView (instead of the url).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM