Removing List’s cell separators in SwiftUI

Currently, as of Xcode 11.1, Apple provides no way for developers to specify a cell separator style for SwiftUI’s List.

Having run into this issue myself, I finally stumbled upon a workaround:

UITableView.appearance().separatorStyle = .none

List seems to respect the UITableView appearance proxy. While this may change in future iOS releases, it’s a good enough solution for the time being.

There is one major caveat - UITableView.appearance() affects the appearance of all Lists in the application. How can we restrict our desired appearance to a single screen?

We utilize a view’s lifecycle events, View.onAppear and View.onDisappear, to set and then unset our custom appearance for a given view.

List {
    Text("a")
    Text("b")
    Text("c")
    Text("d")
}.onAppear {
    UITableView.appearance().separatorStyle = .none
}.onDisappear {
    UITableView.appearance().separatorStyle = .singleLine
}

While this works, it seems rather unwieldly and odd. We can further simplify this code by wrapping part of it in a ViewModifier.

public struct ListSeparatorStyleNoneModifier: ViewModifier {
    public func body(content: Content) -> some View {
        content.onAppear {
            UITableView.appearance().separatorStyle = .none
        }.onDisappear {
            UITableView.appearance().separatorStyle = .singleLine
        }
    }
}

extension View {
    public func listSeparatorStyleNone() -> some View {
        modifier(ListSeparatorStyleNoneModifier())
    }
}

As you can see, we’ve wrapped our appearance setting code into a neat little view modifier. Our example can now be reduced to:

List {
    Text("a")
    Text("b")
    Text("c")
    Text("d")
}.listSeparatorStyleNone()

Note: There is still one issue that we haven’t solved. While view lifecycle events allow us to set/unset the appearance, they affect all views in a given screen. The subject of our modifier must be destroyed for the appearance to restore to its original state, and thus we cannot prevent it from affecting sibling views. We will tackle this problem in a future post.

 
11
Kudos
 
11
Kudos

Now read this

PresentationLink broken in Xcode 11 beta 3

PresentationLink (in SwiftUI) seems to be broken in Xcode 11 beta 3. It succeeds in presenting a modal view controller the first time, but stops working thereafter. As noted in this StackOverflow post, this seems to occur when embedding... Continue →