在 SwiftUI 中使用参数初始化 @StateObject [英] Initialize @StateObject with a parameter in SwiftUI

查看:58
本文介绍了在 SwiftUI 中使用参数初始化 @StateObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道目前(在询问时,第一个 Xcode 12.0 Beta)是否有一种方法可以使用来自初始化程序的参数来初始化 @StateObject.

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 initializer.

更具体地说,这段代码可以正常工作:

To be more specific, this snippet of code works fine:

struct MyView: View {
  @StateObject var myObject = MyObject(id: 1)
}

但这不会:

struct MyView: View {
  @StateObject var myObject: MyObject

  init(id: Int) {
    self.myObject = MyObject(id: id)
  }
}

据我了解,@StateObject 的作用是让视图成为对象的所有者.我目前使用的解决方法是像这样传递已经初始化的 MyObject 实例:

From what I understand the role of @StateObject is to make the view the owner of the object. The current workaround I use is to pass the already initialized MyObject instance like this:

struct MyView: View {
  @ObservedObject var myObject: MyObject

  init(myObject: MyObject) {
    self.myObject = myObject
  }
}

但现在,据我所知,创建对象的视图拥有它,而这个视图没有.

But now, as far as I understand, the view that created the object owns it, while this view does not.

谢谢.

推荐答案

这里是解决方案的演示.使用 Xcode 12b 测试.

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)")
    }
}

这篇关于在 SwiftUI 中使用参数初始化 @StateObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆