Nic*_*lli 3 observable swift swiftui ios17
随着 iOS 17 引入的新@Observable
宏,我们现在可以通过以下方式使用环境对象
@Environment(MyType.self) var myTypeObj
Run Code Online (Sandbox Code Playgroud)
现在,如果myTypeObj
有一些属性,请调用它myProperty
,我想使用$
语法将其作为绑定传递到某处,Swift 抱怨它找不到该变量。例如,
Picker("My Picker", selection: $myTypeObj.myProperty) { // we get an error on this line
ForEach(1 ... 50, id: \.self) { num in
...
}
}
Run Code Online (Sandbox Code Playgroud)
我们收到一条错误消息Cannot find $myTypeObj in scope
:这是 Swift 的错误还是我做错了什么?
在 iOS 17 中你必须使用 Bindable。
@Observable
class AppState {
var isOn: Bool = false
}
struct ContentView: View {
@Environment(AppState.self) private var appState
var body: some View {
@Bindable var bindable = appState
VStack {
Toggle("Is On", isOn: $bindable.isOn)
}
.padding()
}
}
#Preview {
ContentView()
.environment(AppState())
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
519 次 |
最近记录: |