Perry Wang
Perry Wang

Reputation: 209

SwiftUI fullScreenCover using enum keeps open and close automatically on iOS 16

As I said in the title, when I open sheet B in sheet A, and modify the content in onAppear, it will cause the sheet continiously present and dismiss in iOS 16. (I tested on iOS 16.2 and 16.3, and they all have this problem)

But on iOS 17 it works as expected.

import SwiftUI
enum CameraSheet:String, Identifiable{
    var id: String{
        self.rawValue
    }
    case aaa,bbb
}
class ViewModel: ObservableObject {
    @Published var sheet: CameraSheet? = nil
}
class ViewModel1: ObservableObject {
    @Published var toggle: Bool = false
}
struct ContentView: View {
    @StateObject var viewModel = ViewModel()
    @StateObject var viewModel1 = ViewModel1()
    var body: some View {
        let _ = Self._printChanges()
        VStack {
            Text("ShowSheet A")
                .onTapGesture {
                    viewModel.sheet = .aaa
                }
        }
        .fullScreenCover(item: $viewModel.sheet) { item in
            if item == .aaa {
                Button("AAA"){
                    showBBB()
                }
            }
            if item == .bbb {
                Button("AAA"){
                    showAAA()
                }
                .onAppear{
                    viewModel1.toggle.toggle()//<--------Cause the cover loops forever
                }
            }
        }
    }
    func showBBB() {
        viewModel.sheet = .bbb
    }
    func showAAA() {
        viewModel.sheet = .aaa
    }
}

result

Upvotes: 0

Views: 142

Answers (1)

malhal
malhal

Reputation: 30756

@StateObject is just for Combine pipeline or delegate callbacks, you'll need to learn @State and @Binding for your view model data. You might also need to learn computed vars and computed bindings.

Upvotes: 0

Related Questions