Making SwiftUI views with clear backgrounds?

922 Views Asked by At

I've tried any number of methods to get the white background here to be clear. Nothing seems to work.

List over bluebackground

struct OverlayChatView: View {
    var body: some View {
        ZStack {
            Color.clear
            List(0 ..< 5) { item in
                ChatMessageCell()
            }
            .listRowBackground(Color.clear)
            .background(Color.clear)
        }
    }
}

struct ChatMessageCell: View {
    var body: some View {
        HStack {
            Image(systemName: "person.crop.circle")
                .aspectRatio(1.0, contentMode: .fill)
            Text("This is a chat message of certain length to try to force a wrap in the preview.")
        }
    }
}

struct OverlayChatView_Previews: PreviewProvider {
    static var previews: some View {
        ZStack {
            Color.blue
                .ignoresSafeArea()
            OverlayChatView()
                .frame(maxWidth: 300.0, maxHeight: 300.0)
                .background(Color.clear)
        }
    }
}

A lot of people seem to be having the problem and some solve it with the non-starter:

.onAppear {
    UITableView.appearance().backgroundColor = UIColor.clear
    UITableViewCell.appearance().backgroundColor = UIColor.clear
}

I can set the individual list item cells to a specific opaque background color. I can't even set the OverlayChatView or List to a solid color, let alone clear.

iOS 14 (simulator, not device)

1

There are 1 best solutions below

3
On

Wrapped with ForEach and set the background color.

struct OverlayChatView: View {
    var body: some View {
        ZStack {
            Color.clear
            List {
                ForEach(0 ..< 5) {  item in //<-- Here
                    ChatMessageCell()
                }
                .listRowBackground(Color.blue) //<-- Here
            }
            .background(Color.clear)
        }
    }
}

Or you can use colorMultiply as well.

struct OverlayChatView: View {
    var body: some View {
        ZStack {
            Color.clear
            List(0 ..< 5) { item in
                    ChatMessageCell()
                
            }.colorMultiply(Color.blue) //<-- Here
            .background(Color.clear)
        }
    }
}