Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make SwiftUI NavigationLink work in edit mode?

I have a list of items. Clicking on one should push a new view to the navigation stack. I notice the NavigationLink doesn't work if the list is in edit mode. Is there a way to control that? I need it to work in edit mode.

List {
    ForEach(segments) { segment in
        NavigationLink(destination: EditSegmentView(segment: segment)) {
            Text(segment.title)
        }
    }.onDelete(perform: onDelete)
     .onMove(perform: onMove)
}.environment(\.editMode, $alwaysTrue)
like image 348
Rob N Avatar asked Jan 26 '23 18:01

Rob N


1 Answers

I now have this working the way I wanted. I used a different NavigationLink initializer, with the tag and selection arguments. It seems to work well, but I don't know if this is the intended use of that initializer, because the documentation is painfully sparse.

@State var segmentSelection: Segment.ID? = nil

var body: some View {
    NavigationView {
        ...
        List {
            ForEach(workout.segments) { segment in
                NavigationLink(destination: EditSegmentView(segment: segment),    
                               tag: segment.id,
                               selection: self.$segmentSelection) {
                                Text(segment.title)
                }
                .onTapGesture(perform: { self.segmentSelection = segment.id })
            }.onDelete(perform: onDelete)
             .onMove(perform: onMove)
        }.environment(\.editMode, Binding.constant(.active))
        ...
    }
}
like image 136
Rob N Avatar answered Jan 29 '23 19:01

Rob N