1

I am curious why this .fullScreenCover display of a view does not update properly with a passed-in parameter unless the parameter is using the @Binding property wrapper. Is this a bug or intended behavior? Is this the fact that the view shown by the fullScreenCover is not lazily generated?

import SwiftUI

struct ContentView: View {
    @State private var showFullScreen = false
    @State private var message = "Initial Message"
    var body: some View {
        VStack {
            Button {
                self.message = "new message"
                showFullScreen = true
            } label: {
                Text("Show Full Screen")
            }

        }.fullScreenCover(isPresented: $showFullScreen) {
            TestView(text: message)
        }
    }
}

struct TestView: View {
    var text: String
    var body: some View {
       Text(text)
    }
}
Kevin McQuown
  • 1,277
  • 2
  • 9
  • 13
  • 1
    use the `.fullScreenCover(item: ...` version. See also this post: https://stackoverflow.com/questions/71937813/state-property-doesnt-change-its-value-as-expected-until-i-add-onchangeof/71938660#71938660 and the docs: https://developer.apple.com/documentation/swiftui/view/fullscreencover(item:ondismiss:content:) – workingdog support Ukraine Apr 20 '22 at 13:32

1 Answers1

3

There is a different .fullScreenCover(item:) for passing in dynamic data, the closure is changed whenever item changes. For more info see the docs and here is an example:

import SwiftUI

struct CoverData: Identifiable {
    var id: String {
        return message
    }
    let message: String
}

struct FullScreenCoverTestView: View {
    @State private var coverData: CoverData?
    
    var body: some View {
        VStack {
            Button {
                coverData = CoverData(message: "new message")
            } label: {
                Text("Show Full Screen")
            }

        }
        .fullScreenCover(item: $coverData, onDismiss: didDismiss) { item in
            TestView(text: item.message)
            .onTapGesture {
                coverData = nil
            }
        }
    }

    func didDismiss() {
        // Handle the dismissing action.
    }

}

struct TestView: View {
    let text: String
    
    var body: some View {
       Text(text)
    }
}
malhal
  • 26,330
  • 7
  • 115
  • 133