Search code examples
swiftmacosswiftuiswiftui-sheet

Set Sheet BackgroundColor Same As System BackgroundColor in macOS SwiftUI


Sheet background color looks perfectly fine(sheet background color sets system background color automatically)
Untill presented view has .white background color, then sheet background color becomes white instead of default background color. (sheet background color becomes same as presented view's bgcolor { which is white } and one can't differentiate between sheet and presented view bgcolor)

Screenshot For customTextView(backColor: .yellow.opacity(0.5)) { Observe Sheet BGColor }

Screenshot For customTextView(backColor: .white) { Sheet BGColor beomes white }

Screenshot For Desired Output

This is Sheet Code

struct customTextView: View {
    @State var backColor: Color
    var body: some View {
        Text("This is SHEET !")
            .font(.largeTitle)
            .padding()
            .background(backColor)
    }
}

How i present that sheet is shown below in code

.sheet(isPresented: $open, content: {
    customTextView(backColor: .white)
        .frame(width: 300, height: 300)
})

Solution

  • Below is the way to set sheet background color as system background color when presented view has .white background color.

    Before macOS 13.3

    .sheet(isPresented: $open, content: {
        customTextView(backColor: .white)
            .frame(width: 300, height: 300)
            // Below line does the work and sets the system bgcolor as sheet bgcolor
            .background(Color(NSColor.windowBackgroundColor))
    })
    

    For macOS 13.3+

    .sheet(isPresented: $open, content: {
        customTextView(backColor: .white)
            .frame(width: 300, height: 300)
            // Below line does the work and sets the system bgcolor as sheet bgcolor
            .presentationBackground(Color(NSColor.windowBackgroundColor))
    })