数日前から、テキストの編集時の保存と新規作成を実装をしているのですが、文字を打ったテキストエディターに新規のfuncをかけても、テキストが上書きされるだけです。
どうしたら保存と新規作成できるでしょうか?
swift
12struct ContentView: View {3 4 @Environment(\.managedObjectContext) private var viewContext 5 @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)], animation: .default) private var items: FetchedResults<Item>6 7 var body: some View {8 9 NavigationView {10 11 List{12 Section(header: Text("Simple Memo")){13 ForEach(items){item in14 NavigationLink(destination: EditView(item: item), label: {Text(item.text ?? "no")})15 }16 }17 18 .toolbar{19 20 21 ToolbarItemGroup(placement: .bottomBar) {22 23 NavigationLink(destination: PostView(), label: {Image(systemName: "square.and.pencil")})24 25 }26 27 28 }29 30 }31 32 33 }34 35 }36 37}38 39 40struct PostView: View {41 @Environment(\.managedObjectContext) private var viewContext 42 @FetchRequest(43 sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],44 animation: .default)45 private var item: FetchedResults<Item>46 @State var textEditorText = ""47 48 var body: some View {49 TextEditor(text: $textEditorText)50 .font(.body)51 .textInputAutocapitalization(.never)52 .onDisappear(perform: additem)53 .frame(width: .infinity, height: .infinity)54 .toolbar {55 56ToolbarItemGroup(placement: .navigationBarTrailing) {57 58Button(action: {additem()}) {Image(systemName: "circle")}59}60}61 }62 63 func additem() {64 withAnimation {65 let newItem = Item(context: viewContext)66 newItem.text = textEditorText 67 try? viewContext.save()68 textEditorText = ""69 }70 }71 72}73 74struct EditView: View {75 76 @Environment(\.managedObjectContext) private var viewContext 77 @State var textEditorText = ""78 var item: Item79 80 init(item: Item) {81 _textEditorText = State(initialValue: item.text ?? "")82 self.item = item 83 }84 85var body: some View {86 TextEditor(text: $textEditorText)87 .font(.body)88 .textInputAutocapitalization(.never).frame(width: .infinity, height: .infinity)89 .onDisappear(perform: {newPost(item: item)})90 91 .toolbar {92 93ToolbarItemGroup(placement: .navigationBarTrailing) {94 95Button(action: {newPost(item: item)}) {Image(systemName: "circle")}96}97}98 99}100 101func newPost(item: Item) {102 if textEditorText != "" {103 item.text = textEditorText 104 try? viewContext.save()105 }106 textEditorText = ""107 }108 109}110

0 コメント