Initialize @StateObject with a parameter in SwiftUI

前端 未结 5 1865
无人共我
无人共我 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:13

    Here is a demo of solution. Tested with Xcode 12b.

    class MyObject: ObservableObject {
        @Published var id: Int
        init(id: Int) {
            self.id = id
        }
    }
    
    struct MyView: View {
        @StateObject private var object: MyObject
        init(id: Int = 1) {
            _object = StateObject(wrappedValue: MyObject(id: id))
        }
    
        var body: some View {
            Text("Test: \(object.id)")
        }
    }
    

提交回复
热议问题