Search code examples
swiftswiftuiswiftui-listswiftui-navigationlink

How do you change the select color of a navigation link in a list


This seams like a simple question, but I can’t find the answer anywhere on google.

When a navigation link is in a list, you can change the color of it to blue with:

.listRowBackground(Color.blue)

But when the navigation link is selected, it turns to systemGray4

Image for reference

How do I change the select color of a navigation link in a list

Here is the sample project in the image above:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
        List {
            NavigationLink("Hello", destination: Text("hello"))
                .listRowBackground(Color.blue)
            NavigationLink("World", destination: Text("world"))
                .listRowBackground(Color.blue)
        }
        }
    }
}

Solution

  • If you keep track of the selected tab, then you can specifically set the color of the list row for the tab that is selected.

    Example:

    struct ContentView: View {
        enum Tab: String, CaseIterable, Identifiable {
            case hello
            case world
    
            var id: String { rawValue }
    
            var title: String {
                switch self {
                case .hello: return "Hello"
                case .world: return "World"
                }
            }
        }
    
        @State private var selectedTab: Tab?
    
        var body: some View {
            NavigationView {
                List {
                    ForEach(Tab.allCases) { tab in
                        NavigationLink(tab.title, tag: tab, selection: $selectedTab) {
                            Text(tab.rawValue)
                        }
                        .listRowBackground(tab == selectedTab ? Color.accentColor : nil)
                    }
                }
            }
        }
    }
    

    When recording a gif of this on the simulator, for some reason it doesn't work properly. Not sure if that's a bug.