【问题标题】:Error referencing EnvironmentObject in view initializer在视图初始化程序中引用 EnvironmentObject 时出错
【发布时间】:2020-11-24 17:05:03
【问题描述】:

我正在尝试在 SwiftUI 视图初始化程序中引用环境对象来设置状态值,但我收到了错误 'self' used before all stored properties are initialized。有没有办法做到这一点,因为您需要引用 self 来访问环境对象?我觉得引用继承的值是您应该能够在视图构造中执行的操作。

struct Example: View {
 
  @EnvironmentObject var object: Items
  @State var ints: Array<Int>
  
  init() {
    self._ints = State(initialValue: Array(repeating: 0, count: self.object.items.count))
  }
}

【问题讨论】:

    标签: constructor swiftui state combine environmentobject


    【解决方案1】:

    Environment 对象是在 init 之后注入的,所以我们应该稍后更新 state,最常见的是 onAppear:

    struct Example: View {
     
      @EnvironmentObject var object: Items
      @State var ints = Array<Int>()         // << just empty
      
      var body: some View {
        Text("Some view here")
         .onAppear {
            self.ints = Array(repeating: 0, count: self.object.items.count)
         }
      }
    }
    

    作为替代,它可以通过与https://stackoverflow.com/a/59368169/12299030中相同的方法使用子视图

    【讨论】:

    • 我考虑过 onAppear hack,但这还不够。 view 需要状态,特别是数组长度,最初才能正确呈现。初始渲染和 onAppear 之后的数组长度不能变化,因为它会导致越界异常。
    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多