Search code examples
listviewsliderswiftuimac-catalyst

SwiftUI on Mac Catalyst - Edit List with Slider


I got a slider in a list:

img1

I enable the move edit mode:

.onMove { source, destination in
    // ...                     
}

img2

Tho now I can't move the slider...

img3

For now I disable the move like this:

.moveDisabled({
    #if targetEnvironment(macCatalyst)
    return true
    #else
    return false
    #endif
}())

Tho that removes all move functionality... I only want to disable the drag.

Is there a way to read the edit button state? To dynamically change .moveDisabled(...)?


Solution

  • I recommend to manage edit mode manually, thus having possibility to track it is real state. Please see below in code idea how to manage it. The code is simplified, w/o real actions, etc., just to demo how to disable move being in .active edit mode.

    Note: using default @Environment(\.editMode) does not work for this purpose, at least in my Xcode 11.2. So it is set as binding to local state, so it is tracked and with List and with our code.

    struct TestEditWithSliderInList: View {
        @State var value = Array(repeating: 0.0, count: 5)
        @State var editMode: EditMode = .inactive
    
        var body: some View {
            NavigationView {
                List {
                    ForEach(0..<5, id: \.self) { i in
                        HStack {
                            Text("Slider \(i)")
                            Slider(value: self.$value[i], in: 0...100)
                        }
                    }
                    .onDelete(perform: {_ in })
                    .onMove(perform: {(_,_) in })
                    .moveDisabled(editMode == .active ? false : true)
                }
                .environment(\.editMode, $editMode)
                .navigationBarItems(trailing: Button(action: {
                    withAnimation {
                        self.editMode = (self.editMode == .active ? .inactive : .active)
                    }
                }) {
                    Text(self.editMode == .active ? "Done" : "Edit")
                })
            }
        }
    }