GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

.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      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

Click to save your free spot now

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

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.