使用@Observable与@Environment结合Swift Macros编译报错,如何解决?
解决@Observable与@Environment结合时的Binding问题
问题原因
@Environment(Note.self) 获取的是 Note 实例本身,而非 Binding<Note>,因此无法使用 $note 语法;直接传入 note.text 是 String 类型,不符合 TextField 所需的 Binding<String> 参数要求。
解决方案
方法一:直接用Bindable包装实例获取属性Binding
修改FormView的body部分,通过Bindable结构体包装note实例,进而获取属性的Binding:
struct FormView: View { @Environment(Note.self) var note var body: some View { Form { TextField("write here", text: Bindable(note).$text) } } }
方法二:使用@Bindable属性包装器(iOS 17+/macOS 14+)
在FormView中用@Bindable包装环境注入的note,之后即可通过$语法访问属性Binding:
struct FormView: View { @Environment(Note.self) private var note @Bindable private var bindableNote: Note { note } var body: some View { Form { TextField("write here", text: $bindableNote.text) } } }
完整可运行代码
import SwiftUI import Observation @Observable class Note { var text = "" } struct ContentView: View { @State var note = Note() var body: some View { FormView() .environment(note) } } struct FormView: View { @Environment(Note.self) var note var body: some View { Form { TextField("write here", text: Bindable(note).$text) } } }
内容的提问来源于stack exchange,提问作者ygee
相关产品推荐
相关产品推荐

