在 TextView 中传递默认文本,同时使用 SwiftUI 保持状态更改
我试图在视图出现时在 TextView 上设置默认文本,同时仍然能够跟踪 TextView 的更改,然后将其传递到 ViewModel。
这是一个看起来像我正在尝试做的小例子。然而这不起作用,它没有像我预期的那样更新状态。我做错了什么吗?
struct NoteView: View {
@State var note = ""
var noteFromOutside: String?
var body: some View {
VStack {
TextField("Write a note...", text: $note)
.onSubmit {
//Do something with the note.
}
}
.onAppear {
if let newNote = noteFromOutside {
note = newNote
}
}
}
}
struct ParentView: View {
var note = "Note"
var body: some View {
VStack {
NoteView(noteFromOutside: note)
}
}
}
I am trying to set a default text on a TextView when the view appears, while being able to still keep track of changes to the TextView that I can then pass on to my ViewModel.
Here is a little example that looks like what I am trying to do. This does however not work, it does not update the state as I would have expected. Am I doing something wrong?
struct NoteView: View {
@State var note = ""
var noteFromOutside: String?
var body: some View {
VStack {
TextField("Write a note...", text: $note)
.onSubmit {
//Do something with the note.
}
}
.onAppear {
if let newNote = noteFromOutside {
note = newNote
}
}
}
}
struct ParentView: View {
var note = "Note"
var body: some View {
VStack {
NoteView(noteFromOutside: note)
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
找到了另一篇文章的答案,解决了我的问题。关键在于@Binding 和init()。
https://stackoverflow.com/a/64526620/12764203
Found this answer to another post which solved my problem. The key was in the @Binding and init().
https://stackoverflow.com/a/64526620/12764203