Post

Replies

Boosts

Views

Activity

Sheet Won't Display in a ContextMenu
So this project is pretty straightforward. I have an item. The use can create, get a closer look at, delete, or edit an item. For some reason, no matter how many different ways I try to do it, the edit part does not work. I've tried moving the sheet outside of the context menu (it only opens the bottom item), I've tried moving it under the list using the first index of the item (it crashes), and finally I've tried it the shown way and it just doesn't do anything. If anyone can come up with a better way to open the edit view for the correct item (preferably using a context menu, but something similar is acceptable) I would really appreciate it. I've provided the project for a better understanding of what I'm trying to do. If you have any questions just leave a comment. Any help would be greatly appreciated. Content View: struct ContentView: View {     @Environment(\.managedObjectContext) var managedObjContext     @ObservedObject var persistence = PersistenceController.shared     @State private var items = PersistenceController.shared.getItems()     @State private var showingEditView = false     @State private var showingAddView = false          var body: some View {         NavigationView{             List{                 Section(""){                     ForEach(items) { item in                         NavigationLink(destination: ItemView(item: item)){                             Text(item.name!)                         }                         .contextMenu{                             Button(action: {                                 self.showingEditView.toggle()                             }){                                 Text("Edit Item")                             }                             .sheet(isPresented: $showingEditView){                                 EditItemView(item: item)                                     .onDisappear(perform: {                                         items = persistence.getItems()                                     })                             }                         }                     }                     .onDelete(perform: { indexSet in                         deleteItem(indexSet: indexSet)                     })                 }             }             .listStyle(InsetGroupedListStyle())             .cornerRadius(10)             .navigationBarTitle("My Items")             .navigationBarItems(trailing: addButton)             .onAppear(perform: {                 items = persistence.getItems()             })             .sheet(isPresented: $showingAddView){                 AddItemView()                     .onDisappear(perform: {                         items = persistence.getItems()                     })             }         }     }          var addButton: some View {         Button(action: {             showingAddView.toggle()         }){             Text("Add an Item").bold()         }     }          func deleteItem(indexSet: IndexSet){         withAnimation{             indexSet.map {                 items[$0] }                         .forEach(managedObjContext.delete)                          persistence.contextSave()             items = persistence.getItems()         }     } } Item View: struct ItemView: View{     @State var item: Item     var body: some View{         Text(item.name ?? "No Name")     } } Add View: struct AddItemView: View{     @Environment(\.dismiss) var dismiss     @ObservedObject var persistence = PersistenceController.shared     @State private var name = ""     var body: some View {         Form{             TextField("Item Name", text: $name)             Button(action:{                 persistence.addItem(name: name)                 dismiss()             }){                 Text("Add Item")             }         }     } } Edit View: struct EditItemView: View{     @Environment(\.dismiss) var dismiss     @ObservedObject var persistence = PersistenceController.shared     @State var item: Item     @State private var name = ""     var body: some View {         Form{             TextField("Item Name", text: $name)             Button(action:{                 persistence.addItem(name: name)                 dismiss()             }){                 Text("Add Item")             }         }         .onAppear{             name=item.name ?? "No Name"         }     } } Persistence File: class PersistenceController : ObservableObject{     static let shared = PersistenceController()     let container: NSPersistentContainer          init(inMemory: Bool = false) {         container = NSPersistentContainer(name: "Test")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     }     static var preview: PersistenceController = {         let result = PersistenceController(inMemory: true)         let viewContext = result.container.viewContext         for _ in 0..<10 {             let newItem = Item(context: viewContext)             newItem.id = UUID()             newItem.name = "Test"         }         do {             try viewContext.save()         } catch {             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }         return result     }()     func getItems() -> [Item] {         let context = container.viewContext         var request = NSFetchRequest<Item>()         request = Item.fetchRequest()         request.entity = NSEntityDescription.entity(forEntityName: "Item", in: context)         do {             let items = try context.fetch(request)             if items.count == 0 { return []}             return items.sorted(by: {$0.name! > $1.name!})         } catch {             print("**** ERROR: items fetch failed \(error)")             return []         }     }          func addItem(name: String){         let context = container.viewContext         let item = Item(context: context)         item.id = UUID()         item.name = name                  contextSave()     }          func contextSave() {         let context = container.viewContext         if context.hasChanges {             do {                 try context.save()                 self.objectWillChange.send()             } catch {                 print("**** ERROR: Unable to save context \(error)")             }         }     } } Data Model:
1
0
1k
Jun ’22
Broken Date List
I need help optimizing and fixing my date list builder. Basically the user should be able to build a list of dates in a sheet and it be shown on the original view and go back to that page to add more. Dates should not be repeated hence why I use a set. Issue: But when the user adds the first date it doesn't show until a second date is added. After some troubleshooting with print I've found that the problem isn't adding the first item to the list, but the ForEach not working until there is a second item. I've included code for a visual representation of my goal. If you have any questions please leave a comment. Any help would be greatly appreciated. Thanks! import SwiftUI struct ContentView: View {     @State private var dates = Set<Date>()     @State private var isDatesShowing = false     var body: some View {         NavigationView{                 Form{                     Section(""){                         addDatesButton                         Section{                             ForEach(dates.sorted(by: <),id: \.self){ date in                                 Text(date, style: .date)                                     .bold()                                     .foregroundColor(.white)                             }                         }                     }                 }                 .navigationBarTitle("List of Dates")                 .sheet(isPresented: $isDatesShowing){                     AddToDateView(dates: $dates)                 }         }         .preferredColorScheme(.dark)     }     var addDatesButton: some View{         Button(action: {             isDatesShowing.toggle()         }){             Text("Select Dates")                 .bold()         }     } } struct AddToDateView: View {     @Environment(\.dismiss) var dismiss     @Binding var dates: Set<Date>     @State var date = Date()          var body: some View {         NavigationView{             Form{                 DatePicker(selection: $date, in: Date.now..., displayedComponents: .date) {                     Text("Select a date")                 }                 .datePickerStyle(WheelDatePickerStyle())                 Button(action:{                     dates.insert(date)                 }){                     Text("Add Date")                 }                 Section("Dates"){                     ForEach(dates.sorted(by: <),id: \.self){ date in                         Button(action: {                             dates.remove(date)                         }){                             Text(date, style: .date)                                 .bold()                                 .foregroundColor(.white)                         }                     }                 }             }             .cornerRadius(10)             .navigationBarItems(trailing: submitButton)                  }     }          var submitButton: some View{         Button(action: {             dismiss()         }){             Text("Submit")                 .bold()         }     } }
1
0
703
Jun ’22
Airdropping Core Data
So I know this is probably a stretch, but is there any way to airdrop an object from core data? From what I understand airdrop is only used with links, but is there a way to convert the data of a core data object into a file, convert the file into a link, send it via airdrop, and convert it back into a file, and then add that object from a file to another user's core data storage? Any help would be greatly appreciated. Thanks!!
1
0
1.3k
Jul ’22
Resetting a View With a Tab Item
So I have a TabView in my app and I want to go back to the original view when that tabItem is pressed. For example, when you open the App Store and go to the games tab, click on a game. It takes you to a navigation link to a new view. You can either go back to the first page by pressing the arrow, or by tapping the “games” tabItem again. I want to be able to press my tabItem in a subview of the same tab to go back to the original view that the tab is assigned to. Any help would be greatly appreciated! Thanks.
1
0
833
Jul ’22
Core Data
So I was just following along with CodeWithChris's video on make a persistent data storage (https://youtu.be/O7u9nYWjvKk) and I got to the part where he says to include the subclass NSManagedObject to the family and person classes. I have a very similar program with recipe and list of recipes, but when I add "NSManagedObject" I get an error: < unknown >:0: error: stored property '_title' requires an initial value CoreData.NSManagedObject:2:12: note: superclass 'NSManagedObject' requires all stored properties to have initial values open class NSManagedObject : NSObject { < unknown > :0: error: stored property '_calories' requires an initial value CoreData.NSManagedObject:2:12: note: superclass 'NSManagedObject' requires all stored properties to have initial values open class NSManagedObject : NSObject { etc. Unsure of how to fix it. Any help would be greatly appreciated. Code in case I'm missing something RecipeList: import Foundation import CoreData class RecipeList:NSManagedObject, Identifiable{     @Published var recipeList:[Recipe]     init(){         recipeList=[]     }     func addRecipe(recipe: Recipe){         self.recipeList.append(recipe)     }     func removeRecipe(loc: Int){         self.recipeList.remove(at: loc)     }     func getList() -> Array<Recipe>{         return recipeList     } } Recipe: import Foundation import UIKit import CoreData class Recipe:NSManagedObject, Identifiable{     @Published var title: String     @Published var calories: String     @Published var ingredients: Array<String>     @Published var instructions: Array<String>     @Published var totalTime: String     @Published var notes: String     init(title: String, calories: String, ingredients: Array<String>, instructions: Array<String>, totalTime: String, notes: String){         self.title=title         self.calories=calories         self.ingredients=ingredients         self.instructions=instructions         self.totalTime=totalTime         self.notes=notes     } }
0
0
369
May ’22
Toolbar Above Keyboard
I would like to implement the “Toolbar” kind of thing above the keyboard shown in the image that includes an up and down arrow to iterate through text fields and a done button to dismiss the keyboard. How do I do this? Thanks!
0
0
339
May ’22
Airdrop CoreData
I need to share a singular instance of an object created in core data. Every video I've found that showed how to do this used outdated code and I was wondering if anyone had a working way to either create the airdrop button (because I don't even know how to do that yet, or make it so that the data is share is a duplicate of the object from the sharers device. Thanks! This is the entity that needs to be shared via airdrop:
0
0
309
Jun ’22
NavBar Format
How has GitHub formatted their navigation bar like this? The title is aligned with the back button and add button, the search bar is inside instead of under, and they have buttons alone the bottom that filter the list. Is there a view object that shortcuts this? If you understand even one part of that I would appreciate that information. Thanks!
0
0
342
Jun ’22
Calendar That Stores Data
Does anyone know the best way to store core data using a calendar? The only way I could think is adding a date attribute and every time the date is changed on the calendar changing the NSPredicate to that date and if there isn’t one creating a new instance with that date as it’s date value. I’m certain this is not the best method, but I couldn’t think of any other, but I know I’m very limited in my SwiftUI knowledge. So any guidance would be greatly appreciated. For more insight into what I’m looking for see my previous post asking for advice on what to change about my own method: https://developer.apple.com/forums/thread/708915
0
0
918
Jun ’22
TabView Item Back to Main View
So I have a TabView in my app and I want to go back yo the main view when that tabItem is pressed. For example, when you open the App Store and go to the games tab, click on a game. It takes you to a navigation link to a new view. You can either go back to the first page by pressing the arrow, or by tapping the “games” tabItem again. I want to be able to press my tabItem in a subview of the same tab to go back to the original view that the tab is assigned to.
0
0
621
Jun ’22
AirDropping Core Data
So I know this is probably a stretch, but is there any way to airdrop an object from core data? From what I understand airdrop is only used with links, but is there a way to convert the data of a core data object into a file, convert the file into a link, send it via airdrop, and convert it back into a file, and then add that object from a file to another user's core data storage? Any help would be greatly appreciated. Thanks!!
0
0
640
Jun ’22
Tab item but that takes you back to main view
So I have a TabView in my app and I want to go back yo the main view when that tabItem is pressed. For example, when you open the App Store and go to the games tab, click on a game. It takes you to a navigation link to a new view. You can either go back to the first page by pressing the arrow, or by tapping the “games” tabItem again. I want to be able to press my tabItem in a subview of the same tab to go back to the original view that the tab is assigned to.
0
0
637
Jul ’22