小编Giu*_*lli的帖子

当应用于 Binding 时,在 SwiftUI 中展开可选的 @State

我正在寻找一个干净的解决方案来解决这个 SwiftUI 挑战。

以下代码可以编译,但无法工作,因为@State属性超出了ContentView范围。

import SwiftUI

struct ContentView: View {
  var state: LocalState?
  
  var body: some View {
    if let state = state {
      Toggle("Toggle", isOn: state.$isOn)
    }
  }
}

extension ContentView {
  struct LocalState {
    @State var isOn: Bool
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    VStack {
      ContentView(
        state: .init(isOn: false)
      )
      .border(Color.red)
      
      ContentView()
        .border(Color.red)
    }
    
  }
}
Run Code Online (Sandbox Code Playgroud)

由于以下原因,以下代码无法编译:

可选类型“ContentView.LocalState?”的值 必须展开以引用包装基类型“ContentView.LocalState”的成员“isOn”

似乎是$$state.isOn原件state而不是未包装的 …

ios swift swiftui

4
推荐指数
1
解决办法
880
查看次数

标签 统计

ios ×1

swift ×1

swiftui ×1