iOS

SwiftUI Tip: How to Remove Line Separators in List View


The List view in SwiftUI is very similar to the table view in UIKit. It is also designed for developers to present a list of items row by row. By default, each row of data is separated by a line separator. In UIKit, you can easily control the appearance and color of the line separator. Unfortunately, there is no official way to remove line separators in SwiftUI. That said, we can make use of the UIKit API to tweak the line separator of the List view in SwiftUI. In this article, we will show you how this can be done.

Editor’s note: If you are new to SwiftUI, you can first check out the introductory tutorial.

Removing Line Separator in UIKit

In UIKit, to hide or remove the separator in table view, you can set the separatorColor property of the table view to .clear like this:

Alternatively, you can set the separator style to .none to remove the separator:

However, if you’ve used the List view in SwiftUI, you know that it doesn’t come with a modifier to remove the line separator or control its appearance. Thankfully, you can utilize the UIKit API to change the appearance of the List view.

Removing Line Separator in SwiftUI List

To remove the line separator in SwiftUI, you can tweak the List view by attaching the onAppear modifier and call the appearance API of UITableView to disable the line separator:

Once you apply the code above to a List, all the line separators of a list view should be removed.

removing-line-separator-swiftui-list

The catch of this tweak is that the change affects all list views of your app, which means the line separators of all list views are removed. Say, if you have another list view that requires the separators, you will need to change the separator style back to the original value like this:

Creating a Custom View Modifier

In order to make this tweak more SwiftUI friendly, we can create a view modifier for the separator style like this:

Here, we created a custom view modifier named ListSeparatorStyle that is designed to modify the separator style. Now, if you want to hide the line separator of a list view, you can attach the ListSeparatorStyle like this:

Alternatively, you can pass .singleLine to the modifier if you want to enable the line separator.

I hope Apple will provide an official way to control the appearance of the line separator. But right now, you may use this approach to remove the separator.

Does this solution work for you? Please leave a comment below and let me know.

Tutorial
Creating an Immersive User Experience with Haptic Feedback in iOS
SwiftUI
Building Collection Views in SwiftUI with LazyVGrid and LazyHGrid
iOS
How To Scan QR Code Using AVFoundation Framework
Shares