Search code examples
iosswiftuiswiftui-listios16

Swift / iOS 16 Empty SwiftUI List Background Color


My app is built in SwiftUI and mostly works as is with iOS 16 apart from a couple of design quirks which I'm currently working on a fix for.

One of the quirks is the background colours of lists. Previously I have used Introspect to set the color of the background on the lists but as Lists have been reimplemented in iOS16 this no longer works.

I have solved this for iOS 16 devices by using the new scrollContentBackground modifier:

List() {
   some foreach logic here
}
.background(color)
.scrollContentBackground(.hidden)

This works as expected apart from one issue.

When the list is empty the background color is ignored, It shows a white or black background (Not even the grouped background colours) depending on the light or dark mode setting.

Has anybody else come across this issue (or am I doing something wrong?) and if so what solutions have you come up with?

Thanks, C


Solution

  • May not work for everyone but I have a solute for my own problem.

    I am using an overlay to present a message when the list is empty so I decided to do the old ZStack trick in here and it seems to work as expected.

    Example:

    List() {
        ForEach(data, id: \.id) { item in
          // some foreach logic here
        }
    }
    .background(Color.red)
    .scrollContentBackground(.hidden)
    .overlay(Group {
        if(data.isEmpty) {
            ZStack() {
                Color.red.ignoresSafeArea()
                Text("Empty List!")
            }
        }
    })
    

    Hope this helps somebody else!