Post

Replies

Boosts

Views

Activity

SwiftUI Map menu / chrome placement — three approaches (overlay, ZStack + safeAreaPadding, safeAreaInset): which one is best practice?
Hi everyone, I’m building a full-screen Map (MapKit + SwiftUI) with persistent top/bottom chrome (menu buttons on top, session stats + map controls on bottom). I have three working implementations and I’d like guidance on which pattern Apple recommends long-term (gesture correctness, safe areas, Dynamic Island/home indicator, and future compatibility). Version 1 — overlay(alignment:) on Map Idea: Draw chrome using .overlay(alignment:) directly on the map and manage padding manually. Map(position: $viewModel.previewMapCameraPosition, scope: mapScope) { UserAnnotation { UserLocationCourseMarkerView(angle: viewModel.userCourse - mapHeading) } } .mapStyle(viewModel.mapType.mapStyle) .mapControls { MapUserLocationButton().mapControlVisibility(.hidden) MapCompass().mapControlVisibility(.hidden) MapPitchToggle().mapControlVisibility(.hidden) MapScaleView().mapControlVisibility(.hidden) } .overlay(alignment: .top) { mapMenu } // manual padding inside .overlay(alignment: .bottom) { bottomChrome } // manual padding inside Version 2 — ZStack + .safeAreaPadding Idea: Place the map at the back, then lay out top/bottom chrome in a VStack inside a ZStack, and use .safeAreaPadding(.all) so content respects safe areas. ZStack(alignment: .top) { Map(...).ignoresSafeArea() VStack { mapMenu Spacer() bottomChrome } .safeAreaPadding(.all) } Version 3 — .safeAreaInset on the Map Idea: Make the map full-bleed and then reserve top/bottom space with safeAreaInset, letting SwiftUI manage insets Map(...).ignoresSafeArea() .mapStyle(viewModel.mapType.mapStyle) .mapControls { MapUserLocationButton().mapControlVisibility(.hidden) MapCompass().mapControlVisibility(.hidden) MapPitchToggle().mapControlVisibility(.hidden) MapScaleView().mapControlVisibility(.hidden) } .safeAreaInset(edge: .top) { mapMenu } // manual padding inside .safeAreaInset(edge: .bottom) { bottomChrome } // manual padding inside Question I noticed: Safe-area / padding behavior – Version 2 requires the least extra padding and seems to create a small but partial safe-area spacing automatically. – Version 3 still needs roughly the same manual padding as Version 1, even though it uses safeAreaInset. Why doesn’t safeAreaInset fully handle that spacing? Rotation crash (Metal) When using Version 3 (safeAreaInset + ignoresSafeArea), rotating the device portrait↔landscape several times triggers a Metal crash: failed assertion 'The following Metal object is being destroyed while still required… CAMetalLayer Display Drawable' The same crash can happen with Version 1, though less often. I haven’t tested it much with Version 2. Is this a known issue or race condition between Map’s internal Metal rendering and view layout changes? Expected behavior What’s the intended or supported interaction between safeAreaInset, safeAreaPadding, and overlay when embedding persistent chrome inside a SwiftUI Map? Should safeAreaInset normally remove the need for manual padding, or is that by design?
0
0
122
Nov ’25
Index out of range, SwiftUI
Hello import SwiftUI enum When: String { case Today case Week case Month case Year } struct ChartView: View { var when: When @EnvironmentObject var millilitriInseritiModel: MillilitriInseritiModel var valoriAsseX: [String]{ if when == When.Week{ return ["M", "T", "W", "T", "F", "S", "S"] } else if when == When.Month{ return ["7", "14", "21", "28"] } else if when == When.Year{ return ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"] } return [] } var valoriAsseY: [Double]{ return [] } var dates: [Date] = [Date(), Date().addingTimeInterval(86400), Date().addingTimeInterval(86400 * 2)] @State var valori: [Double] = [1000, 2000, 3000, 1000, 2000, 1000, 2000, 3000, 1000, 2000, 3000] var altezzaRettangolo: [Double]?{ var altezze: [Double] = [] for i in 0..<valori.count{ altezze.append(valori[i]) } return altezze } @State var animation: Bool = false var body: some View{ HStack(alignment: .bottom, spacing: 8, content: { ForEach(valoriAsseX.indices){ i in VStack{ RoundedRectangle(cornerRadius: 3) .fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .top, endPoint: .bottom)) .frame(width: 40, height: animation ? CGFloat(altezzaRettangolo?[i] ?? 0) / 7 : 0) .animation(.easeInOut) Text(valoriAsseX[i]) .fontWeight(.semibold) .multilineTextAlignment(.leading) .onTapGesture { withAnimation{ valori[i] += 100 } } } } }) .padding() .onAppear { animation = true } .onDisappear { animation = false } } } struct ChartView_Previews: PreviewProvider { static var previews: some View { ChartView(when: When.Year) } } As you might notice, in the previews I set when to When.Year, that is crashing the app because the array valoriAsseX is bigger than the array altezzaRettangolo, so when I iterate it in the ForEach loop it crashes, I can't find any way to solve this, I tried an if let but it is crashing anyway, any ideas? Thank you
5
0
2.2k
Jun ’21
Filter in ForEach SwiftUI
Hello I implemented the filter function in my ForEach loop, and it works just with the valori property but not with the date property , is there a way to let it filter also the date? I tried to remove the dateFormatter but it didn't work. Here is the code import SwiftUI let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter }() struct Test4: View { @State private var text: String = "" var body: some View { NavigationView{ if !lifetimes.isEmpty{ List{ Section(header: Text("")){ TextField("Search", text: $text) } Section(header: Text("")){ ForEach(lifetimes.filter { text.isEmpty || "\($0)".contains(text) }, id: \.id){ lifetimeInputs in HStack{ Text("\(lifetimeInputs.valori, specifier: "%.0f")") Spacer() Text("\(dateFormatter.string(from: lifetimeInputs.date))") } } } } .listStyle(InsetGroupedListStyle()) .navigationTitle("All History") } else{ VStack{ Text("No Data") .font(.largeTitle) .fontWeight(.semibold) .foregroundColor(.secondary) } .padding(.bottom) .navigationTitle("All History") } } } } struct LifetimeInputsModel: Identifiable { var id = UUID() var valori: Double var date: Date } var lifetimes: [LifetimeInputsModel] = [ LifetimeInputsModel(valori: 300, date: Date()), LifetimeInputsModel(valori: 200, date: Date() + 86400) ] Thank you
2
0
2.9k
Jun ’21
CloudKit and CoreData synchronization
Hello I am developing an app with SwiftUI using CoreData and iCloudKit to sync data between platforms. The problem is that the iCloud background update is not being triggered when staying in the application. If I make changes on both systems, the changes are being pushed, however not visible on the other device. I need to reload the app, close the app and open again. I already enabled iCloud capability, background notifications and push notifications. This is my persistentContainer var persistentContainer: NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "Test7") container.loadPersistentStores(completionHandler: {(StoreDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy return container }() func saveContext() { let context = persistentContainer.viewContext if context.hasChanges{ do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } This is my model class ItemsModel: ObservableObject { init() { readData() } @Published var dataInputs: [Item] = [] let context = persistentContainer.viewContext func readData(){ let request: NSFetchRequest<Item> = Item.fetchRequest() do { let results = try context.fetch(request) self.dataInputs = results } catch { print(error.localizedDescription) } } func addItem(todo: String, date: Date){ let entity = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item entity.todo = todo entity.date = date do { try context.save() self.dataInputs.append(entity) } catch { print(error.localizedDescription) } } func deleteItems(indexSet: IndexSet){ for index in indexSet{ do { let obj = dataInputs[index] context.delete(obj) try context.save() let index = dataInputs.firstIndex(of: obj) dataInputs.remove(at: index!) } catch { print(error.localizedDescription) } } } } and this is my view struct ContentView: View { @EnvironmentObject var items: ItemsModel var body: some View { NavigationView{ List { ForEach(items.dataInputs) { item in Text("Item at \(item.date!)") } .onDelete(perform: items.deleteItems) } .toolbar { Button { items.addItem(todo: "Hello", date: Date()) } label: { Image(systemName: "plus") } } } } } Thank you
3
0
2.5k
Jun ’21
Refresh value in view SwiftUI
Hello I am making a counter app using Core Data to store the value that the user has reached, the problem is that in the DetailView the value changes just if I close the view and reopen it, how can I change the value immediately when the user taps the button? ContentView: struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)], animation: .default) private var items: FetchedResults<Item> @State private var isShown: Bool = false var body: some View { NavigationView{ List { Section(header: Text("All counters")){ ForEach(items) { item in NavigationLink( destination: DetailView(item: item) .environment(\.managedObjectContext, viewContext) , label: { HStack{ Text(item.name ?? "") .font(.title3) .fontWeight(.semibold) Spacer() Text("\(item.value, specifier: "%.0f")") .font(.title3) .fontWeight(.semibold) } }) } .onDelete(perform: { indexSet in deleteItems(offsets: indexSet) print(items) }) } } .listStyle(InsetGroupedListStyle()) .sheet(isPresented: $isShown, content: { AddView() .environment(\.managedObjectContext, viewContext) }) .navigationBarTitle("Counter") .toolbar { Menu { Button(action: { isShown.toggle() }) { Text("Add Item") } EditButton() } label: { Image(systemName: "plus") .font(.title) } } } } private func deleteItems(offsets: IndexSet) { withAnimation { offsets.map { items[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { print(error.localizedDescription) } } } } DetailView: struct DetailView: View { @Environment(\.managedObjectContext) private var viewContext var item: Item var body: some View { VStack(alignment: .center, spacing: nil, content: { Text("\(item.value, specifier: "%.0f")") .font(.largeTitle) .fontWeight(.bold) .padding(.top) Spacer() HStack{ Button(action: { withAnimation{ item.value += 1 do { try viewContext.save() } catch { print(error.localizedDescription) } } }, label: { Image(systemName: "plus") }) Button(action: { withAnimation{ item.value -= 1 do { try viewContext.save() } catch { print(error.localizedDescription) } } }, label: { Image(systemName: "minus") }) } .foregroundColor(.primary) Spacer() }) .navigationBarTitle(item.name ?? "", displayMode: .inline) } } Thank you
1
0
5.9k
Jun ’21
App increases size even if I delete data (Core Data)
Hello I noticed that in my app, when I add data (I am using Core Data) the size of the app increases, as expected, the problem occurs when I delete data, the size of the app remains unchanged and sometimes increases, I thought there was an error in the my code and so I created, from scratch, a project for iOS with SwiftUI and Core Data enabled (the default template that Xcode provides) and also with the SwiftUI & Core Data default app the same problem happens. Is there a way to fix it or is there an explanation for this? Thank you!
3
0
1.6k
Aug ’21
MatchedGeometryEffect SwiftUI
Hello I am using matched Geometry Effect to make animations and transitions, the problem is that when I press to start the animation, the object being animated, in this case Text, is duplicated during the transition, and then when I press again to get it back to its original position, no animation takes place, how can I fix it. Here is the code: struct ContentView: View { @StateObject var numberViewModel = NumberViewModel() @Namespace var animation var body: some View { GeometryReader { geo in NavigationView{ ZStack { ScrollView{ LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) { ForEach(numbers){ number in NumberView(numberViewModel: numberViewModel, animation: animation, number: number) .onTapGesture { withAnimation(.easeInOut(duration: 1)){ numberViewModel.selected = number numberViewModel.tapped = true } } } } } if numberViewModel.tapped{ NumberTappedView(animation: animation, numberViewModel: numberViewModel) .position( x: geo.frame(in:.global).midX, y: geo.frame(in:.global).midY ) .onTapGesture { withAnimation(.easeInOut(duration: 1)){ numberViewModel.selected = Number(number: 0) numberViewModel.tapped = false } } } } } } } } struct NumberView: View { @ObservedObject var numberViewModel: NumberViewModel var animation: Namespace.ID var number: Number var body: some View{ GroupBox{ if !(numberViewModel.selected.number == number.number){ Text("\(number.number)") .font(.largeTitle) .frame(width: 100, height: 100, alignment: .center) .matchedGeometryEffect(id: number.number, in: animation) } } } } struct Number: Identifiable { var id = UUID() var number: Int } var numbers: [Number] = [ Number(number: 1), Number(number: 2) ] struct NumberTappedView: View { var animation: Namespace.ID @ObservedObject var numberViewModel: NumberViewModel var body: some View{ GroupBox{ Text("\(numberViewModel.selected.number)") .font(.largeTitle) .frame(width: 200, height: 200, alignment: .center) .matchedGeometryEffect(id: numberViewModel.selected.number, in: animation) } } } class NumberViewModel: ObservableObject { @Published var selected: Number = Number(number: 0) @Published var tapped: Bool = false } Thank You!
1
0
3.1k
Aug ’21
Rotate View around an other View SwiftUI
Hello I created a custom shape in SwiftUI and I am trying to rotate it around a circle, but it works just on the top part of the circle, can you help me make it rotate exactly around the circle? (And also can I get the same effect using radians? How?) Here is the code: import SwiftUI struct MyGameView: View { @State private var degress: Double = 0 let timer = Timer.publish(every: 0.05, on: .main, in: .common).autoconnect() var body: some View { VStack{ ZStack{ Circle() .frame(width: 80) ZStack{ Circle() .stroke(lineWidth: 1) .frame(width: 300) BallonShape() .scaledToFit() .scaleEffect(0.2) .foregroundColor(.red) .rotationEffect(.degrees(degress), anchor: .bottom) .offset(x: 0, y: -170) } } } .onReceive(timer) { input in withAnimation(.easeIn(duration: 0.05).speed(10)){ degress += 1 } } } } struct BallonShape: Shape { func path(in rect: CGRect) -> Path { Path { path in path.move(to: CGPoint(x: rect.midX, y: (rect.maxY + rect.midY) / 2)) path.addCurve(to: CGPoint(x: rect.midX, y: rect.minY), control1: CGPoint(x: (rect.midX + rect.minX) / 2, y: rect.minY), control2: CGPoint(x: (rect.midX + rect.minX) / 2, y: rect.minY)) path.addCurve(to: CGPoint(x: rect.midX, y: (rect.maxY + rect.midY) / 2), control1: CGPoint(x: (rect.midX + rect.maxX) / 2, y: rect.minY), control2: CGPoint(x: (rect.midX + rect.maxX) / 2, y: rect.minY)) } } } Thank You very much!
3
0
2.2k
Sep ’21
Core Data Predicate Filter By Today's Date
Hello I am using a SwiftUI @FetchRequest to displays Core Data items, one of the properties of the entity is date, and I want to filter items by today's Date, this is the @FetchRequest: @FetchRequest( entity: Book.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Book.date, ascending: true)], predicate: NSPredicate(format: "date == %@"), animation: .default) var books: FetchedResults<Book> How do I complete the NSPredicate to make it work? (I know that there are no arguments in the predicate yet) Thank You!
1
0
4.8k
Sep ’21
SwiftUI Map menu / chrome placement — three approaches (overlay, ZStack + safeAreaPadding, safeAreaInset): which one is best practice?
Hi everyone, I’m building a full-screen Map (MapKit + SwiftUI) with persistent top/bottom chrome (menu buttons on top, session stats + map controls on bottom). I have three working implementations and I’d like guidance on which pattern Apple recommends long-term (gesture correctness, safe areas, Dynamic Island/home indicator, and future compatibility). Version 1 — overlay(alignment:) on Map Idea: Draw chrome using .overlay(alignment:) directly on the map and manage padding manually. Map(position: $viewModel.previewMapCameraPosition, scope: mapScope) { UserAnnotation { UserLocationCourseMarkerView(angle: viewModel.userCourse - mapHeading) } } .mapStyle(viewModel.mapType.mapStyle) .mapControls { MapUserLocationButton().mapControlVisibility(.hidden) MapCompass().mapControlVisibility(.hidden) MapPitchToggle().mapControlVisibility(.hidden) MapScaleView().mapControlVisibility(.hidden) } .overlay(alignment: .top) { mapMenu } // manual padding inside .overlay(alignment: .bottom) { bottomChrome } // manual padding inside Version 2 — ZStack + .safeAreaPadding Idea: Place the map at the back, then lay out top/bottom chrome in a VStack inside a ZStack, and use .safeAreaPadding(.all) so content respects safe areas. ZStack(alignment: .top) { Map(...).ignoresSafeArea() VStack { mapMenu Spacer() bottomChrome } .safeAreaPadding(.all) } Version 3 — .safeAreaInset on the Map Idea: Make the map full-bleed and then reserve top/bottom space with safeAreaInset, letting SwiftUI manage insets Map(...).ignoresSafeArea() .mapStyle(viewModel.mapType.mapStyle) .mapControls { MapUserLocationButton().mapControlVisibility(.hidden) MapCompass().mapControlVisibility(.hidden) MapPitchToggle().mapControlVisibility(.hidden) MapScaleView().mapControlVisibility(.hidden) } .safeAreaInset(edge: .top) { mapMenu } // manual padding inside .safeAreaInset(edge: .bottom) { bottomChrome } // manual padding inside Question I noticed: Safe-area / padding behavior – Version 2 requires the least extra padding and seems to create a small but partial safe-area spacing automatically. – Version 3 still needs roughly the same manual padding as Version 1, even though it uses safeAreaInset. Why doesn’t safeAreaInset fully handle that spacing? Rotation crash (Metal) When using Version 3 (safeAreaInset + ignoresSafeArea), rotating the device portrait↔landscape several times triggers a Metal crash: failed assertion 'The following Metal object is being destroyed while still required… CAMetalLayer Display Drawable' The same crash can happen with Version 1, though less often. I haven’t tested it much with Version 2. Is this a known issue or race condition between Map’s internal Metal rendering and view layout changes? Expected behavior What’s the intended or supported interaction between safeAreaInset, safeAreaPadding, and overlay when embedding persistent chrome inside a SwiftUI Map? Should safeAreaInset normally remove the need for manual padding, or is that by design?
Replies
0
Boosts
0
Views
122
Activity
Nov ’25
Create ML with SwiftUI
Hello Does anyone know how to use real time image recognition in SwiftUI with a Create ML model. Thank you
Replies
1
Boosts
0
Views
1.8k
Activity
Jun ’21
Index out of range, SwiftUI
Hello import SwiftUI enum When: String { case Today case Week case Month case Year } struct ChartView: View { var when: When @EnvironmentObject var millilitriInseritiModel: MillilitriInseritiModel var valoriAsseX: [String]{ if when == When.Week{ return ["M", "T", "W", "T", "F", "S", "S"] } else if when == When.Month{ return ["7", "14", "21", "28"] } else if when == When.Year{ return ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"] } return [] } var valoriAsseY: [Double]{ return [] } var dates: [Date] = [Date(), Date().addingTimeInterval(86400), Date().addingTimeInterval(86400 * 2)] @State var valori: [Double] = [1000, 2000, 3000, 1000, 2000, 1000, 2000, 3000, 1000, 2000, 3000] var altezzaRettangolo: [Double]?{ var altezze: [Double] = [] for i in 0..<valori.count{ altezze.append(valori[i]) } return altezze } @State var animation: Bool = false var body: some View{ HStack(alignment: .bottom, spacing: 8, content: { ForEach(valoriAsseX.indices){ i in VStack{ RoundedRectangle(cornerRadius: 3) .fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .top, endPoint: .bottom)) .frame(width: 40, height: animation ? CGFloat(altezzaRettangolo?[i] ?? 0) / 7 : 0) .animation(.easeInOut) Text(valoriAsseX[i]) .fontWeight(.semibold) .multilineTextAlignment(.leading) .onTapGesture { withAnimation{ valori[i] += 100 } } } } }) .padding() .onAppear { animation = true } .onDisappear { animation = false } } } struct ChartView_Previews: PreviewProvider { static var previews: some View { ChartView(when: When.Year) } } As you might notice, in the previews I set when to When.Year, that is crashing the app because the array valoriAsseX is bigger than the array altezzaRettangolo, so when I iterate it in the ForEach loop it crashes, I can't find any way to solve this, I tried an if let but it is crashing anyway, any ideas? Thank you
Replies
5
Boosts
0
Views
2.2k
Activity
Jun ’21
Filter in ForEach SwiftUI
Hello I implemented the filter function in my ForEach loop, and it works just with the valori property but not with the date property , is there a way to let it filter also the date? I tried to remove the dateFormatter but it didn't work. Here is the code import SwiftUI let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter }() struct Test4: View { @State private var text: String = "" var body: some View { NavigationView{ if !lifetimes.isEmpty{ List{ Section(header: Text("")){ TextField("Search", text: $text) } Section(header: Text("")){ ForEach(lifetimes.filter { text.isEmpty || "\($0)".contains(text) }, id: \.id){ lifetimeInputs in HStack{ Text("\(lifetimeInputs.valori, specifier: "%.0f")") Spacer() Text("\(dateFormatter.string(from: lifetimeInputs.date))") } } } } .listStyle(InsetGroupedListStyle()) .navigationTitle("All History") } else{ VStack{ Text("No Data") .font(.largeTitle) .fontWeight(.semibold) .foregroundColor(.secondary) } .padding(.bottom) .navigationTitle("All History") } } } } struct LifetimeInputsModel: Identifiable { var id = UUID() var valori: Double var date: Date } var lifetimes: [LifetimeInputsModel] = [ LifetimeInputsModel(valori: 300, date: Date()), LifetimeInputsModel(valori: 200, date: Date() + 86400) ] Thank you
Replies
2
Boosts
0
Views
2.9k
Activity
Jun ’21
CloudKit and CoreData synchronization
Hello I am developing an app with SwiftUI using CoreData and iCloudKit to sync data between platforms. The problem is that the iCloud background update is not being triggered when staying in the application. If I make changes on both systems, the changes are being pushed, however not visible on the other device. I need to reload the app, close the app and open again. I already enabled iCloud capability, background notifications and push notifications. This is my persistentContainer var persistentContainer: NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "Test7") container.loadPersistentStores(completionHandler: {(StoreDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy return container }() func saveContext() { let context = persistentContainer.viewContext if context.hasChanges{ do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } This is my model class ItemsModel: ObservableObject { init() { readData() } @Published var dataInputs: [Item] = [] let context = persistentContainer.viewContext func readData(){ let request: NSFetchRequest<Item> = Item.fetchRequest() do { let results = try context.fetch(request) self.dataInputs = results } catch { print(error.localizedDescription) } } func addItem(todo: String, date: Date){ let entity = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item entity.todo = todo entity.date = date do { try context.save() self.dataInputs.append(entity) } catch { print(error.localizedDescription) } } func deleteItems(indexSet: IndexSet){ for index in indexSet{ do { let obj = dataInputs[index] context.delete(obj) try context.save() let index = dataInputs.firstIndex(of: obj) dataInputs.remove(at: index!) } catch { print(error.localizedDescription) } } } } and this is my view struct ContentView: View { @EnvironmentObject var items: ItemsModel var body: some View { NavigationView{ List { ForEach(items.dataInputs) { item in Text("Item at \(item.date!)") } .onDelete(perform: items.deleteItems) } .toolbar { Button { items.addItem(todo: "Hello", date: Date()) } label: { Image(systemName: "plus") } } } } } Thank you
Replies
3
Boosts
0
Views
2.5k
Activity
Jun ’21
Repeating function in SwiftUI
Hello Is there way to keep calling a function (efficiently) while the view is on screen, without using a timer, in SwiftUI?
Replies
3
Boosts
0
Views
4.7k
Activity
Aug ’23
Refresh value in view SwiftUI
Hello I am making a counter app using Core Data to store the value that the user has reached, the problem is that in the DetailView the value changes just if I close the view and reopen it, how can I change the value immediately when the user taps the button? ContentView: struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)], animation: .default) private var items: FetchedResults<Item> @State private var isShown: Bool = false var body: some View { NavigationView{ List { Section(header: Text("All counters")){ ForEach(items) { item in NavigationLink( destination: DetailView(item: item) .environment(\.managedObjectContext, viewContext) , label: { HStack{ Text(item.name ?? "") .font(.title3) .fontWeight(.semibold) Spacer() Text("\(item.value, specifier: "%.0f")") .font(.title3) .fontWeight(.semibold) } }) } .onDelete(perform: { indexSet in deleteItems(offsets: indexSet) print(items) }) } } .listStyle(InsetGroupedListStyle()) .sheet(isPresented: $isShown, content: { AddView() .environment(\.managedObjectContext, viewContext) }) .navigationBarTitle("Counter") .toolbar { Menu { Button(action: { isShown.toggle() }) { Text("Add Item") } EditButton() } label: { Image(systemName: "plus") .font(.title) } } } } private func deleteItems(offsets: IndexSet) { withAnimation { offsets.map { items[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { print(error.localizedDescription) } } } } DetailView: struct DetailView: View { @Environment(\.managedObjectContext) private var viewContext var item: Item var body: some View { VStack(alignment: .center, spacing: nil, content: { Text("\(item.value, specifier: "%.0f")") .font(.largeTitle) .fontWeight(.bold) .padding(.top) Spacer() HStack{ Button(action: { withAnimation{ item.value += 1 do { try viewContext.save() } catch { print(error.localizedDescription) } } }, label: { Image(systemName: "plus") }) Button(action: { withAnimation{ item.value -= 1 do { try viewContext.save() } catch { print(error.localizedDescription) } } }, label: { Image(systemName: "minus") }) } .foregroundColor(.primary) Spacer() }) .navigationBarTitle(item.name ?? "", displayMode: .inline) } } Thank you
Replies
1
Boosts
0
Views
5.9k
Activity
Jun ’21
App increases size even if I delete data (Core Data)
Hello I noticed that in my app, when I add data (I am using Core Data) the size of the app increases, as expected, the problem occurs when I delete data, the size of the app remains unchanged and sometimes increases, I thought there was an error in the my code and so I created, from scratch, a project for iOS with SwiftUI and Core Data enabled (the default template that Xcode provides) and also with the SwiftUI & Core Data default app the same problem happens. Is there a way to fix it or is there an explanation for this? Thank you!
Replies
3
Boosts
0
Views
1.6k
Activity
Aug ’21
MatchedGeometryEffect SwiftUI
Hello I am using matched Geometry Effect to make animations and transitions, the problem is that when I press to start the animation, the object being animated, in this case Text, is duplicated during the transition, and then when I press again to get it back to its original position, no animation takes place, how can I fix it. Here is the code: struct ContentView: View { @StateObject var numberViewModel = NumberViewModel() @Namespace var animation var body: some View { GeometryReader { geo in NavigationView{ ZStack { ScrollView{ LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) { ForEach(numbers){ number in NumberView(numberViewModel: numberViewModel, animation: animation, number: number) .onTapGesture { withAnimation(.easeInOut(duration: 1)){ numberViewModel.selected = number numberViewModel.tapped = true } } } } } if numberViewModel.tapped{ NumberTappedView(animation: animation, numberViewModel: numberViewModel) .position( x: geo.frame(in:.global).midX, y: geo.frame(in:.global).midY ) .onTapGesture { withAnimation(.easeInOut(duration: 1)){ numberViewModel.selected = Number(number: 0) numberViewModel.tapped = false } } } } } } } } struct NumberView: View { @ObservedObject var numberViewModel: NumberViewModel var animation: Namespace.ID var number: Number var body: some View{ GroupBox{ if !(numberViewModel.selected.number == number.number){ Text("\(number.number)") .font(.largeTitle) .frame(width: 100, height: 100, alignment: .center) .matchedGeometryEffect(id: number.number, in: animation) } } } } struct Number: Identifiable { var id = UUID() var number: Int } var numbers: [Number] = [ Number(number: 1), Number(number: 2) ] struct NumberTappedView: View { var animation: Namespace.ID @ObservedObject var numberViewModel: NumberViewModel var body: some View{ GroupBox{ Text("\(numberViewModel.selected.number)") .font(.largeTitle) .frame(width: 200, height: 200, alignment: .center) .matchedGeometryEffect(id: numberViewModel.selected.number, in: animation) } } } class NumberViewModel: ObservableObject { @Published var selected: Number = Number(number: 0) @Published var tapped: Bool = false } Thank You!
Replies
1
Boosts
0
Views
3.1k
Activity
Aug ’21
@FetchRequest in a class, SwiftUI
Hello I was trying to use @FetchRequest in a class, but found it doesn't work, so I was wondering if there was a way to use something that works like @FetchRequest in a class? Thank You!
Replies
1
Boosts
0
Views
895
Activity
Sep ’21
Date in Swift printed is wrong
Hello I wanted to know why when I print(Date()) the date is printed but two hours before? Example If I print(Date()) and the actual date is 2021-09-10 22:33:41 +0000, it prints 2021-09-10 20:33:41 +0000 instead of 2021-09-10 22:33:41 +0000. Why does this happen? Thank You!
Replies
5
Boosts
0
Views
6k
Activity
Sep ’21
Rotate View around an other View SwiftUI
Hello I created a custom shape in SwiftUI and I am trying to rotate it around a circle, but it works just on the top part of the circle, can you help me make it rotate exactly around the circle? (And also can I get the same effect using radians? How?) Here is the code: import SwiftUI struct MyGameView: View { @State private var degress: Double = 0 let timer = Timer.publish(every: 0.05, on: .main, in: .common).autoconnect() var body: some View { VStack{ ZStack{ Circle() .frame(width: 80) ZStack{ Circle() .stroke(lineWidth: 1) .frame(width: 300) BallonShape() .scaledToFit() .scaleEffect(0.2) .foregroundColor(.red) .rotationEffect(.degrees(degress), anchor: .bottom) .offset(x: 0, y: -170) } } } .onReceive(timer) { input in withAnimation(.easeIn(duration: 0.05).speed(10)){ degress += 1 } } } } struct BallonShape: Shape { func path(in rect: CGRect) -> Path { Path { path in path.move(to: CGPoint(x: rect.midX, y: (rect.maxY + rect.midY) / 2)) path.addCurve(to: CGPoint(x: rect.midX, y: rect.minY), control1: CGPoint(x: (rect.midX + rect.minX) / 2, y: rect.minY), control2: CGPoint(x: (rect.midX + rect.minX) / 2, y: rect.minY)) path.addCurve(to: CGPoint(x: rect.midX, y: (rect.maxY + rect.midY) / 2), control1: CGPoint(x: (rect.midX + rect.maxX) / 2, y: rect.minY), control2: CGPoint(x: (rect.midX + rect.maxX) / 2, y: rect.minY)) } } } Thank You very much!
Replies
3
Boosts
0
Views
2.2k
Activity
Sep ’21
Collapse button NavigationView SideBar SwiftUI
Hello How can I remove the Collapse button that is on the navigationBar in iPadOS? Thank You!
Replies
5
Boosts
0
Views
4.5k
Activity
Apr ’22
Core Data Predicate Filter By Today's Date
Hello I am using a SwiftUI @FetchRequest to displays Core Data items, one of the properties of the entity is date, and I want to filter items by today's Date, this is the @FetchRequest: @FetchRequest( entity: Book.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Book.date, ascending: true)], predicate: NSPredicate(format: "date == %@"), animation: .default) var books: FetchedResults<Book> How do I complete the NSPredicate to make it work? (I know that there are no arguments in the predicate yet) Thank You!
Replies
1
Boosts
0
Views
4.8k
Activity
Sep ’21
Returning different dates from CoreData objects using NSPredicate
Hello If I have this array: var objects = [ Object(value: 100, date: Date(), imageTemplate: "30"), Object(value: 200, date: Date(), imageTemplate: "20"), Object(value: 400, date: Date() + 84000, imageTemplate: "10") ] How can I count how many different dates are in the array using NSPredicate? In this case it should return 2. Thank You!
Replies
6
Boosts
0
Views
1k
Activity
Sep ’21