Post

Replies

Boosts

Views

Activity

Button That Changes Label on Click
So I’ve looked this up so many times and tried every way I’ve found using a @State variable and nothing works. I need a button that toggles between SystemImage: “Star” to SystemImage: “Star.fill” when clicked. And I want it to happen when it’s clicked. Everything I’ve tried only changes when I close and reopen the view because it happens on appearance. Is there any way to make it change instantly? Thanks for any help!
1
0
387
May ’22
Nav View inside Nav View in a Sheet
So I have a sheet View for when I add a recipe to my program, but when I add an instruction I want the user to be able to click their entry and check it to see if it is correct so what I’ve done is add a text view to enlarge it, but when I go to the view it shows the nav bar of the previous view like this: This only happens when I use a sheet.
1
0
382
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
324
May ’22
Searching a Data Model
I need to be able to search my list of recipes given a string. I’m unsure how to filter a data model in core data though. I tried a ForEach(container){ recipe in, but it said it gave me an error. Anyone know the correct way in the scrappy way doesn’t work? Thanks data controller: import Foundation import CoreData class DataController: ObservableObject {     let container = NSPersistentContainer(name: "RecipeModel")     init() {         container.loadPersistentStores { desc, error in             if let error = error {                 print("Failed to load the data \(error.localizedDescription)")             }         }     }     func save(context: NSManagedObjectContext) {         do {             try context.save()             print("Data saved")         } catch {             print("The data could not be saved")         }     }     func addRecipe(title: String, ingredients: [String], instructions: [String], notes: String, context: NSManagedObjectContext){         let recipe = Recipe(context: context)         recipe.id = UUID()         recipe.date = Date()         recipe.title = title         recipe.ingredients = ingredients         recipe.instructions = instructions         recipe.notes = notes         save(context: context)     }     func editRecipe(recipe: Recipe, title: String, ingredients: [String], instructions: [String], notes: String, context: NSManagedObjectContext){         recipe.title = title         recipe.ingredients = ingredients         recipe.instructions = instructions         recipe.notes = notes         save(context: context)import Foundation     }     func updateDate(recipe: Recipe, context: NSManagedObjectContext){         recipe.date=Date()         save(context: context)     } }
1
0
441
May ’22
Option Prompt on Button Hold
So I want to implement the same feature many apple made have which is an gray list of options when something is held. An example of this is when you hold down an iMessage chat before you open it and it gives the options to “Pin”, “Hide Alerts”, and “Delete” and shown here: Additionally when you hold down an app as if you were going to delete it a menu of options show up: Using a button how can I do this on a long hold? Any help or any direction toward help is greatly appreciated. All the best!
1
0
750
May ’22
Data Persistence using Core Data
So I created a program without selecting “use core data” and realized after trying to make a persistence data storage that it helps very much so I created a new program and selected it this time and copied everything over. It provided a file called “Persistence” and the contentView file had a bunch of stuff already filled in (Also something called the title of the program). I have the data I need saved to the persistent data storage narrowed down to a singular array, but none of the videos I found online showed this version of xcode that supplied a “Persistence” file when using core data so I’m unsure how to use it. I will provide the contentView and Persistence file for context. The array I need saved is called mainList in contentView. ContentView: import SwiftUI import CoreData struct ContentView: View {     var mainList = [RecipeList(),RecipeList(),RecipeList(),RecipeList(),RecipeList()]          @Environment(\.managedObjectContext) private var viewContext     @FetchRequest(         sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],         animation: .default)     private var items: FetchedResults<Item>     var body: some View {         NavigationView {             List {                 ForEach(items) { item in                     NavigationLink {                         Text("Item at \(item.timestamp!, formatter: itemFormatter)")                     } label: {                         Text(item.timestamp!, formatter: itemFormatter)                     }                 }                 .onDelete(perform: deleteItems)             }             .toolbar {                 ToolbarItem(placement: .navigationBarTrailing) {                     EditButton()                 }                 ToolbarItem {                     Button(action: addItem) {                         Label("Add Item", systemImage: "plus")                     }                 }             }             Text("Select an item")         }     }     private func addItem() {         withAnimation {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     }     private func deleteItems(offsets: IndexSet) {         withAnimation {             offsets.map { items[$0] }.forEach(viewContext.delete)             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     } } private let itemFormatter: DateFormatter = {     let formatter = DateFormatter()     formatter.dateStyle = .short     formatter.timeStyle = .medium     return formatter }() struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)     } } Persistence: import CoreData struct PersistenceController {     static let shared = PersistenceController()     static var preview: PersistenceController = {         let result = PersistenceController(inMemory: true)         let viewContext = result.container.viewContext         for _ in 0..<10 {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()         }         do {             try viewContext.save()         } catch {             // Replace this implementation with code to handle the error appropriately.             // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }         return result     }()     let container: NSPersistentCloudKitContainer     init(inMemory: Bool = false) {         container = NSPersistentCloudKitContainer(name: "ReciStorage")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 /*                  Typical reasons for an error here include:                  * The parent directory does not exist, cannot be created, or disallows writing.                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.                  * The device is out of space.                  * The store could not be migrated to the current model version.                  Check the error message to determine what the actual problem was.                  */                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     } } Image showing the thing named the title of the program that I’m certain is relevant to the persisting data storage: Also I’m unsure what I need to replace those comments with and what subclasses I should add to existing swift files like “codable” for example. Any help would be greatly appreciated.
2
1
1.7k
May ’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
348
May ’22