NoteView.swift (2370B)
1 // 2 // NoteView.swift 3 // txtodo 4 // 5 // Created by FIGBERT on 8/11/20. 6 // 7 8 import SwiftUI 9 10 struct NoteView: View { 11 @Environment(\.managedObjectContext) var managedObjectContext 12 @ObservedObject var task: Task 13 @State var note: String 14 @State var config: NoteViewConfig 15 16 var body: some View { 17 return HStack { 18 Image(systemName: "minus") 19 .padding(.trailing) 20 if !config.editing { 21 Text(note) 22 .onTapGesture(count: 2) { 23 self.config.editing = true 24 } 25 } else { 26 TextField("edit note", text: $config.editingCache, onCommit: { 27 if let index = self.task.notes.firstIndex(of: self.note) { 28 self.managedObjectContext.performAndWait { 29 self.task.notes[index] = self.config.editingCache 30 try? self.managedObjectContext.save() 31 } 32 } 33 self.config.editing = false 34 }) 35 } 36 Spacer() 37 if config.showingDelete { 38 Image(systemName: "trash.circle.fill") 39 .font(.system(size: 25)) 40 .foregroundColor(.red) 41 .onTapGesture { 42 if let index = self.task.notes.firstIndex(of: self.note) { 43 self.managedObjectContext.performAndWait { 44 self.task.notes.remove(at: index) 45 try? self.managedObjectContext.save() 46 } 47 } 48 } 49 } 50 } 51 .offset(x: config.offset) 52 .gesture( 53 DragGesture() 54 .onChanged({ value in 55 config.offset = value.translation.width 56 }) 57 .onEnded({ value in 58 if -config.offset > 15 { 59 config.showingDelete.toggle() 60 } 61 config.offset = 0 62 }) 63 ) 64 } 65 } 66 67 struct NoteViewConfig { 68 var editing: Bool = false 69 var showingDelete: Bool = false 70 var offset: CGFloat = 0 71 var editingCache: String 72 }