ios – Objects related to enums in Swift lack ObservableObject and @Printed wrappers, stopping state modifications from updating the UI

0
20
ios – Objects related to enums in Swift lack ObservableObject and @Printed wrappers, stopping state modifications from updating the UI


I’ve a MainViewModel that holds an array of enums with related objects. Nevertheless, once I use this in a SwiftUI view, the variable loses its @Printed wrapper, and the UI would not replace or get notified of modifications. How can I protect the @Printed standing of the variable?

Here is my code seem like:

// Enum with related sorts
enum ViewType: Hashable, Identifiable {
    case .a(ViewModelA)
    case .b(ViewModelB)
    case .c(ViewModelC)
}

// courses utilized in related sorts
class ViewModelA: ObservableObject {
    @Printed var listIndex: Int = 1
    //another properties
}

class ViewModelB: ObservableObject {
    @Printed var identify: String = "hiya"
     //another properties
}

class ViewModelC: ObservableObject {
    @Printed var isOn: Bool = false
     //another properties
}

// then I create an array in my mainViewModel
// to make use of in my SwiftUI view
class MainViewModel: ObservableObject {
    @Printed var viewTypeArray: [ViewType] = [] // add objects to it primarily based on the backend response (assume I've 4 objects)
}


// then I exploit the viewModel for my part
struct MyView: View {
    @ObservedObject viewModel: MainViewModel

    init(viewModel: MainViewModel) {
        self.viewModel = viewModel
    }

    var physique: some View {
        ForEach(viewModel.viewTypeArray) { view in
            case .a(let viewModelA):
               // I show one thing
               // I unfastened the ObservableObject wrapper
               // then I lose the connection to @Printed wrapper properties ex: `listIndex`
               // and no ui updates will set off right here
            case .b(let viewModelB):
               // I show one thing
               // I unfastened the ObservableObject wrapper
               // then I lose the connection to @Printed properties ex: `identify`
               // and no ui updates will set off right here
            case .c(let viewModelC):
               // I show one thing
               // I unfastened the ObservableObject wrapper
               // then I lose the connection to @Printed properties ex: `isOn`
               // and no ui updates will set off right here
        }
    }
}

I attempted utilizing an ObservableObject wrapper for every little one ViewModel (e.g., ViewModelA, ViewModelB) to take care of a direct reference to the view, however this did not work. I wish to use an enum with related sorts, together with @ObservableObject and @Printed wrappers, to make sure that modifications correctly replace the SwiftUI view.

LEAVE A REPLY

Please enter your comment!
Please enter your name here