在 TextView 中传递默认文本,同时使用 SwiftUI 保持状态更改

发布于 2025-01-13 07:32:15 字数 747 浏览 1 评论 0原文

我试图在视图出现时在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撕心裂肺的伤痛 2025-01-20 07:32:15

找到了另一篇文章的答案,解决了我的问题。关键在于@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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文