首页 > 解决方案 > Edit Text Editor SwiftUI

问题描述

I am trying to edit the text of a binding value from another view. But text editor does not allow me to do so.

First I need to see the previous value of selectedNote.title in TextEditor and then I should be able to edit the title.

struct EditNotePageView: View {
    @Binding var selectedNote: CDNoteModel!
    @State var text = ""
    var body: some View {
        TextEditor(selectedNote.title!, text: $text)
    }
}

I also tried like this. I can see my selectedNote.title in the simulator but when I tap on it it does nothing.

 struct EditNotePageView: View {
    @Binding var selectedNote: CDNoteModel!
    @State var text = ""
    var body: some View {
        Text(selectedNote.title!)
            .onTapGesture {
                text = selectedNote.title!
                TextEditor(text: $text)
            }
    }
}

enter image description here

标签: swiftuibindingtext-editor

解决方案


ZStack Text 和 textEditor 用一点点 .onAppear 解决了这个问题

  struct EditNotePageView: View {
    @Binding var selectedNote: CDNoteModel!
    @State var text = ""
    var body: some View {
        ZStack(alignment: .leading){
            Text(selectedNote.title!)
                .onAppear {
                    text = selectedNote.title!
                }
            TextEditor(text: $text)
        }
    }
}

推荐阅读