Selection color of a NavigationLink in List was different in Simulator and Device (SwiftUI)
Asked Answered
T

3

6

I have a list with some NavigationLinks as OutlineGroup:

List {
  OutlineGroup(bundle.topics, children: \.children) { topic in
    NavigationLink(destination: DetailView(topic: topic)) {
      Label(topic.name, systemImage: topic.children != nil ? "folder" : "doc")
    }
  }
}

My problem is that the selection color was different on the iPad Air device and the iPad Air simulator. On the simulator, the background color of a selected NavigationLink was gray and the disclosure indicator is still visible.

enter image description here

But on the real iPad Air device, the selection color is blue – the same blue as the disclosure indicator and it wasn't visible on a selected row.

enter image description here

Any idea, why the color is difference? Can I manually set the selection background color?

Trelu answered 16/11, 2021 at 16:50 Comment(1)
I noticed this difference is between iOS 15 and iOS 16. On 15 the selection color was gray while 16 is accent. There are also discrepancies in Apple's own applications. For instance, the redesigned System Settings in Ventura 13.2.1 has a accent selection color, while Finder, Photos, etc. still uses light gray.Woven
B
4

Add an accentColor(_:) modifier to the list with the color you want to use.

List {
   OutlineGroup(bundle.topics, children: \.children) { topic in
      NavigationLink(destination: DetailView(topic: topic)) {
         Label(topic.name, systemImage: topic.children != nil ? "folder" : "doc")
      }
   }
}
.accentColor(.gray)

The only problem is accentColor(_:) is getting deprecated. Apple suggests to use tint(_:) but it isn't working. The other option would be to change the asset catalog’s accent color.

Binetta answered 24/1, 2022 at 0:8 Comment(2)
compilers shows a warning that we should use: .tint(...) but it doesn't work i don't know whyUrbannai
I believe the select color may appear differently if there is a selected item in a nested List or equivalent.Caelian
C
2

To properly set the row selection color while keeping the correct tint color for the controls inside the rows, you need to call accentColor twice, like so.

List {
    ForEach(items) { item in 
        ItemView(item)
    }
    .accentColor(.accentColor) // the normal tint for the row content
}
.accentColor(.purple) // the row selection background color
Communitarian answered 24/12, 2022 at 19:14 Comment(0)
K
0

Try using .listRowBackground:

List {
    ForEach(items) { item in 
        ItemView(item)
           .listRowBackground(Color.clear)
    }
}
Kraigkrait answered 27/6 at 1:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.