Search code examples
swiftuiswiftui-list

Ignoring SafeArea for one list row only


I have the following view:

struct Example: View {
    var body: some View {
        List{
            Color.red
                .listRowInsets(EdgeInsets())
            Color.blue
                .listRowInsets(EdgeInsets())
        }
        .listStyle(.grouped)
        List{
            Color.green
                .listRowInsets(EdgeInsets())
            Color.yellow
                .listRowInsets(EdgeInsets())
        }
        .listStyle(.grouped)
        .ignoresSafeArea()
    }
}

which generates the following layout: enter image description here Now, what I actually want is the blue list row in the first list to be as wide as the green and yellow ones in the second list (ignoring the safe area). But I want to keep the red one as wide as it is right now (respecting the safe area). How can I do that? Just adding .ignoresSafeArea() to the blue list row does not have any effect.


Solution

  • The modifier .ignoresSafeArea() only works if a view is already in contact with the edge of the safe area inset. If not, it has no effect, which may be the case for the rows inside the List.

    You could always do it the other way and ignore the safe area insets for the whole List (like you are doing in the second example) and then add padding or row insets on the rows that you want to keep inside the safe area. A GeometryReader can be used to measure the size of the safe area insets:

    var body: some View {
        GeometryReader { proxy in
            VStack {
                List{
                    Color.red
                        .listRowInsets(EdgeInsets())
                        .padding(.leading, proxy.safeAreaInsets.leading)
                        .padding(.trailing, proxy.safeAreaInsets.trailing)
                    Color.blue
                        .listRowInsets(EdgeInsets())
                }
                .listStyle(.grouped)
                .ignoresSafeArea(edges: .horizontal)
    
                List{
                    Color.green
                        .listRowInsets(EdgeInsets())
                    Color.yellow
                        .listRowInsets(EdgeInsets())
                }
                .listStyle(.grouped)
                .ignoresSafeArea()
            }
        }
    }
    

    Screenshot