0

I have an existing app that has a custom background color for List views. I've used the following in older iOS versions to get this to work.

UITableView.appearance().backgroundColor = .clear

With iOS 16 the new way to color the background is with

List {
        Text("Item 1")
        Text("Item 2")
        Text("Item 3")
    }
    .scrollContentBackground(Color.red)  

However, my app's Deployment target is iOS 14. When I add the new code above I get an error stating this is only for iOS 16 and later.

The new Lists are now built on UICollectionView instead of UITableView so I tried

UICollectionView.appearance().backgroundColor = .clear

This didn't work. When I run iOS 16 in the simulator my custom background color does not show up. Any help here would be appreciated.

2 Answers 2

0

You could create a view modifier to add the background in a specific way depending on if the iOS version is 16 or lower.

In your initializer:

if #unavailable(iOS 16, *) {
    UITableView.appearance().backgroundColor = .clear
}

Apply this view modifier to add background when the device is iOS 16

@available(iOS 16, *)
struct ListBackgroundModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .scrollContentBackground(Color.red)
}

extension View {
    @ViewBuilder
    func addBackground() -> some View {
        if #available(iOS 16, *) {
            modifier(ListBackgroundModifier())
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

2024 answer

Xcode 15.4
base SDK: iOS 16
min SDK: iOS 15.0 (for support iPhone 6S+)

For change the SwiftUI List background

var defaultColor: UIColor? = UICollectionView.appearance().backgroundColor

var body: some View {
    VStack {
        List {
            ForEach(items) { item in
                ...
            }
            .listRowSeparator(.hidden)
            .listRowBackground(Color.clear)
        }
        .listStyle(.plain)
        .onAppear {
            UICollectionView.appearance().backgroundColor = UIColor(Color.clear)
        }
        .onDisappear {
            UICollectionView.appearance().backgroundColor = self.defaultColor
        }
    }
    .background(.red)
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.