0

I am trying to keep the selection to remain highlighted when navigating back from the destination of the NavigationLink. This code running on iPhone 14 simulator on iOS 16 deselects the current selection or selects 2 items and the count of selected items at the bottom does not match the highlighted items.

Am I missing something obvious ?

EDIT 1:

  • Need to keep NavigationView for compatibility to iOS 15
  • The issue is the same when using a single selection instead of a Set
import SwiftUI

struct ContentView: View {
    
    struct Ocean: Identifiable, Hashable {
        let name: String
        let id = UUID()
    }

    private var oceans = [
        Ocean(name: "Pacific"),
        Ocean(name: "Atlantic"),
        Ocean(name: "Indian"),
        Ocean(name: "Southern"),
        Ocean(name: "Arctic")
    ]

    @State private var multiSelection = Set<Ocean>()

    var body: some View {
        NavigationView {
            VStack {
                List(oceans, id: \.self, selection: $multiSelection) { ocean in
                    NavigationLink {
                        Text(ocean.name)
                    } label: {
                        Text(ocean.name)
                    }
                }
                Text("\(multiSelection.count) selected")
            }
            .navigationTitle("Oceans")
            .toolbar { EditButton() }
        }
    }
}

enter image description here

Fred Klein
  • 448
  • 6
  • 13

1 Answers1

0

NavigationView is now deprecated, it is best to use NaviagtionStack.

To keep the selections highlighted when navigating back from the NavigationLink, add

 NavigationLink {...}
     .listRowBackground(multiSelection.contains(ocean) ? Color.red : Color.clear)
sumida
  • 268
  • 9
  • Thank you @sumida however I need to keep compatibility to iOS 15 so I cannot use NavigationStack. – Fred Klein May 27 '23 at 09:12
  • My answer works just as well for me with `NavigationView`. Does this not work for you? – sumida May 27 '23 at 14:41
  • it does not work better than the default highlight color. I get the same corrupt selection as in my original example/video: 2 items, one being the second last item that was selected and the other one the last selected item. Am I the only one having this behaviour or is it the same for you too? – Fred Klein May 27 '23 at 22:33
  • I should clarify, I am on MacOS 13.4, using Xcode 14.3 running on ios-16 iPhone. Using ios-15 may well be the source of your problem. – sumida May 28 '23 at 00:44
  • The issue manifested originally with the iPhone 14 simulator on iOS 16.4. I have MacOS 13.3 and Xcode 14.3. – Fred Klein May 28 '23 at 15:41