How can I change the colour of separator in list of SwiftUI?

Viewed 4633

I created a list in SwiftUI. I want to change the color or remove the separator as, In UIKit, we can easily change the color of separator in TableView.

Below is the code and UI(image) of the list in SwiftUI

@State private var users = ["Paul", "Taylor", "Adele"]

var body: some View {

    List(){
                ForEach(users, id: \.self) { user in
                    HStack{
                        Image("helmet").resizable().frame(width: 40, height: 40, alignment: .leading)
                        VStack(alignment : .leading){
                            Text(user).font(.custom("SFProText-Semibold", size: 14))
                            Text("Blu Connect").font(.custom("SFProText-Semibold.ttf", size: 11))
                        }
                    }
                }
                .onDelete(perform: delete)

            }
}

enter image description here

4 Answers

Try this

var body: some View {
        UITableView.appearance().separatorColor = UIColor.blue
        return List(){
            ForEach(users, id: \.self) { user in
                HStack{
                    Image("helmet").resizable().frame(width: 40, height: 40, alignment: .leading)
                    VStack(alignment : .leading){
                        Text(user).font(.custom("SFProText-Semibold", size: 14))
                        Text("Blu Connect").font(.custom("SFProText-Semibold.ttf", size: 11))
                    }
                }
            }
            .onDelete(perform: delete)

        }
    }

This is a kind of global variable, so you are changing the separator colour in all UITableViews from your app (List and Form are using UITableViews under the hood)

iOS 15

From this year, you can apply color to any separator individually with listRowSeparatorTintColor modifier like:

Demo


To remove

From iOS 15, you can use listRowSeparator modifier by passing hidden. Please read this detailed answer for more information and samples.

2021 – Xcode 13 / SwiftUI 3

Change color of separator:

.listRowSeparatorTint(Color.pink)

Hide separator:

.listRowSeparator(.hidden)

You can also swap out the List() element for a ScrollView() element.

Related