BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

.onMove for List with more Sections

Forums > SwiftUI

Hello, I am trying to move items between sections of list. I use default function EditButton(). When I activate it and try to move item from one section to another section it doest't catch in new section and moves back to origin section. Is there any general approach, how to solve it please? Thanks for help Jirka

4      

I'm struggling with this as well. did you make any progress?

3      

You can achieve this behavior if you're not actually using a section header, but have a custom item act as one.

By setting .moveDisabled() to true the item can't be moved. You can then style the header the way you want.

Here's a small example i've tried out.

class SelectionViewModel: ObservableObject {
    struct Item {
        let title: String
        let isHeader: Bool
    }
    @Published var sections: [Item] = [
        .init(title: "Selected", isHeader: true),
        .init(title: "A", isHeader: false),
        .init(title: "B", isHeader: false),
        .init(title: "C", isHeader: false),
        .init(title: "Unselected", isHeader: true),
        .init(title: "D", isHeader: false),
        .init(title: "E", isHeader: false),
        .init(title: "F", isHeader: false),

    ]
}

struct SelectionView: View {
    @ObservedObject var selectionViewModel: SelectionViewModel

    var body: some View {
        List {
            ForEach(selectionViewModel.sections, id: \.title) { item in
                if item.isHeader {
                    Text("Section header \(item.title)")
                        .moveDisabled(true)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding([.top, .bottom])
                        .background(Color.gray)

                } else {
                    Text(item.title)
                        .moveDisabled(item.isHeader)
                }
            }.onMove(perform: { indices, newOffset in
                print("should move")
            })
        }.environment(\.editMode, .constant(.active))
    }
}

struct SelectionView_Previews: PreviewProvider {
    static var previews: some View {
        SelectionView(selectionViewModel: .init())
    }
}

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.