Post

Replies

Boosts

Views

Activity

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.1k
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 Core Data save single values
Hello I am using CoreData in my App and want to save a single Picker value. I could create an entity with an Integer attribute and always edit the first object in the EntityList. But that doesn't sound like a clean solution. The Picker is placed inside a settings view and has to be synced with iCloud. Is there a simple way to do this? Thank You
1
0
713
Oct ’21
Siri Shortcuts with CoreData
Hello I created a simple SwiftUI app with Core Data and I want to be able to add data via the shortcuts app, I created a shortcut that takes some text as input and returns it in uppercase and when I run the shortcut in the shortcuts app, it works, however when I added an "add" function (to save data in the Core Data database) to the intent handle function, and I run it again nothing is saved in the app, here is the code: class MakeUppercaseIntentHandler: NSObject, MakeUppercaseIntentHandling { let persistenceController = PersistenceController() func handle(intent: MakeUppercaseIntent, completion: @escaping (MakeUppercaseIntentResponse) -> Void) { if let inputText = intent.text { let uppercaseText = inputText.uppercased() completion(MakeUppercaseIntentResponse.success(result: add(text: uppercaseText))) } else { completion(MakeUppercaseIntentResponse.failure(error: "The text entred is invalid")) } } func resolveText(for intent: MakeUppercaseIntent, with completion: @escaping (MakeUppercaseTextResolutionResult) -> Void) { if let text = intent.text, !text.isEmpty { completion(MakeUppercaseTextResolutionResult.success(with: text)) } else { completion(MakeUppercaseTextResolutionResult.unsupported(forReason: .noText)) } } func add(text: String) -> String{ let newItem = Item(context: persistenceController.container.viewContext) newItem.text = text do { try persistenceController.container.viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } return text } } Thank You
3
0
1.1k
Dec ’21
SwiftUI & Layout API. Extra trailing closure passed in call
Hello I'm trying to compose a layout using the Layout API. I have already written the code for both the Layout Stack I want to use and the view I am using it in, however I am getting an "Extra trailing closure passed in call" error in the view I am using the Stack in. Here is the code: import SwiftUI struct StairsView: View { var body: some View { Group{ MyStairsStack{ Text("Hello, World!") Text("Hello, World!") Text("Hello, World!") } } } } struct MyStairsStack: Layout{ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize { return .init(width: proposal.width ?? 0, height: proposal.height ?? 0) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) { guard !subviews.isEmpty else { return } let viewSize = maxSize(subViews: subviews) var origin = bounds.origin let maxWidth = bounds.width subviews.forEach { view in if (origin.x + (viewSize.width + 10) >= maxWidth){ origin.x = bounds.origin.x } view.place(at: origin, proposal: proposal) origin.x += (viewSize.width + 10) origin.y += (viewSize.height + 10) } } private func maxSize(subViews: Subviews) -> CGSize{ subViews.map { $0.sizeThatFits(.unspecified) }.reduce(.zero) { currentMax, subviewSize in CGSize( width: max(currentMax.width, subviewSize.width), height: max(currentMax.height, subviewSize.height)) } } } The error is at line 5 Thank You for your time
2
0
1.7k
Jun ’22
'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately.
Hello I'm trying to detect objects with CreateML, but it gives me this warning that I think is breaking my app: 'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately. The classfier.model is a CreatML model that has some images Have any ideas on how to fix it? import UIKit import AVKit import Vision import CoreML class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { &#9;&#9; &#9;&#9;let identifierLabel: UILabel = { &#9;&#9;&#9;&#9;let label = UILabel() &#9;&#9;&#9;&#9;label.backgroundColor = .white &#9;&#9;&#9;&#9;label.textAlignment = .center &#9;&#9;&#9;&#9;label.translatesAutoresizingMaskIntoConstraints = false &#9;&#9;&#9;&#9;return label &#9;&#9;}() &#9;&#9;override func viewDidLoad() { &#9;&#9;&#9;&#9;super.viewDidLoad() &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;// here is where we start up the camera &#9;&#9;&#9;&#9;// for more details visit: https://www.letsbuildthatapp.com/course_video?id=1252 &#9;&#9;&#9;&#9;let captureSession = AVCaptureSession() &#9;&#9;&#9;&#9;captureSession.sessionPreset = .photo &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;guard let captureDevice = AVCaptureDevice.default(for: .video) else { return } &#9;&#9;&#9;&#9;guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return } &#9;&#9;&#9;&#9;captureSession.addInput(input) &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;captureSession.startRunning() &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) &#9;&#9;&#9;&#9;view.layer.addSublayer(previewLayer) &#9;&#9;&#9;&#9;previewLayer.frame = view.frame &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;let dataOutput = AVCaptureVideoDataOutput() &#9;&#9;&#9;&#9;dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue")) &#9;&#9;&#9;&#9;captureSession.addOutput(dataOutput) &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;setupIdentifierConfidenceLabel() &#9;&#9;} &#9;&#9; &#9;&#9;fileprivate func setupIdentifierConfidenceLabel() { &#9;&#9;&#9;&#9;view.addSubview(identifierLabel) &#9;&#9;&#9;&#9;identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32).isActive = true &#9;&#9;&#9;&#9;identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true &#9;&#9;&#9;&#9;identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true &#9;&#9;&#9;&#9;identifierLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true &#9;&#9;} &#9;&#9; &#9;&#9;func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { //&#9;&#9;&#9;&#9;print("Camera was able to capture a frame:", Date()) &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;// !!!Important &#9;&#9;&#9;&#9;// make sure to go download the models at https://developer.apple.com/machine-learning/ scroll to the bottom &#9;&#9;&#9;&#9;guard let model = try? VNCoreMLModel(for: Classfier().model) else { return } &#9;&#9;&#9;&#9;let request = VNCoreMLRequest(model: model) { (finishedReq, err) in &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;//perhaps check the err &#9;&#9;&#9;&#9;&#9;&#9; //&#9;&#9;&#9;&#9;&#9;&#9;print(finishedReq.results) &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;guard let results = finishedReq.results as? [VNClassificationObservation] else { return } &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;guard let firstObservation = results.first else { return } &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;print(firstObservation.identifier, firstObservation.confidence) &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;DispatchQueue.main.async { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.identifierLabel.text = "\(firstObservation.identifier) \(firstObservation.confidence * 100)" &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request]) &#9;&#9;} } Thank you for your time
2
1
4.9k
Jan ’21
@AppStorage with Date in SwiftUI
Hello I want to be able to save Date in @AppStorage, and it works however I was wondering what was the difference between these two extensions, which one is better and why? extension Date: RawRepresentable { static var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long return formatter }() public var rawValue: String { Date.dateFormatter.string(from: self) } public init?(rawValue: String) { self = Date.dateFormatter.date(from: rawValue) ?? Date() } } and extension Date: RawRepresentable { private static let formatter = ISO8601DateFormatter() public var rawValue: String { Date.formatter.string(from: self) } public init?(rawValue: String) { self = Date.formatter.date(from: rawValue) ?? Date() } } Thank You!
5
0
6.2k
Dec ’24
Notify when @FetchRequest changes?
Hello @FetchRequest( entity: Book(), sortDescriptors: [] ) var books: FetchedResults<Book> How can I get notified when books changes? I was thinking about putting this... .onReceive(NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave), perform: { _ in}) ... in my main View but this would notify me if anything gets saved and that is not what I want. I want to get notified just if a certain FetchRequest changes (in this case books)? How can I do that? Thank You!
4
1
2.6k
Jan ’23