Initialize @StateObject with a parameter in SwiftUI

前端 未结 5 1863
无人共我
无人共我 2021-01-03 20:29

I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject with a parameter coming from an

5条回答
  •  青春惊慌失措
    2021-01-03 21:05

    I guess I found a workaround for being able to control the instantiation of a view model wrapped with @StateObject. If you don't make the view model private on the view you can use the synthesized memberwise init, and there you'll be able to control the instantiation of it without problem. In case you need a public way to instantiate your view, you can create a factory method that receives your view model dependencies and uses the internal synthesized init.

    import SwiftUI
    
    class MyViewModel: ObservableObject {
        @Published var message: String
    
        init(message: String) {
            self.message = message
        }
    }
    
    struct MyView: View {
        @StateObject var viewModel: MyViewModel
    
        var body: some View {
            Text(viewModel.message)
        }
    }
    
    public func myViewFactory(message: String) -> some View {
        MyView(viewModel: .init(message: message))
    }
    

提交回复
热议问题