BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Swiping actions on NSManagedObject list

Forums > SwiftUI

Hello again. Two questions:

  1. I'm trying to add swipe actions to my lists of NSManaged Objects (as Edit() "default" option only gives the option for trailing deletion), but I can't find the way to pass "autor" from "ForEach" closure out to swipeActions modifier: it says "Cannot find 'autor' in scope".

  2. By the way, for expert SwiftUI programmers: how can I use this swipe option to edit elements from the list, just in place if possible :-) , taking into account that all of them are NSManagedObjects?

Thank you very much in advance :-)

struct MantenimientoAutoresView: View {

    @Environment(\.managedObjectContext) var moc
    @FetchRequest(sortDescriptors: [SortDescriptor(\.nombre)]) private var autores: FetchedResults<Autor>

    var body: some View {

        List {
            ForEach(autores, id: \.id) { autor in
                Text(autor.nombre ?? "")
            }

            .swipeActions(edge: .trailing) {
                moc.delete(autor)

                }
            }
            // More code below...

   

Your swipeAction is bound to the ForEach, i.e. outside of your closure that gets the autor variable. Try moving it to the Text.

In addition, if you want to be able to delete any eleent in the list, consider using and implementing the onDelete modifier on the ForEach.

   

Yes! What an idiot of mine :-))) Thanks!

About my second question? Any idea? I'm now using this option to access my CoreData objects as Binding ones, in order to load its data the same time I have the option to edit them:

https://stackoverflow.com/questions/59001253/how-should-i-bind-to-a-core-data-entity-string-attribute-within-a-swiftui-view

It works, but I can't use it for in-place-editing on lists, forms or pickers. Even using this sintax:

TextField(Binding(autor.nombre, replacingNilWith: ""))

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.