Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the background behind the stack of sheets in SwiftUI?

Tags:

swiftui

How can I change the background here (black) to another color? I was playing around with an app called Honk, and they've set different backgrounds in some of their sections. I saw something on SO that said it could be done with window.backgroundColor = .magenta but I have no idea where to put that. I assumed it would either be inside the init() or as a property on the highest-level view of my app ie NavigationView, but no luck so far.

enter image description here

Here's a screenshot from Honk for reference:

enter image description here

And another:

enter image description here

like image 694
ragavanmonke Avatar asked Oct 30 '25 21:10

ragavanmonke


2 Answers

As people have rightly pointed out in the comments of the accepted answer that it has become slightly outdated in iOS 17. I just changed the reply by @BFeher to not need as much optional chaining in the function:

private func setWindowBackgroundColor(_ color: UIColor) {
    if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
        let window = windowScene.windows.first
    {
        window.backgroundColor = color
    }
}
like image 52
Ajit Krishna Avatar answered Nov 02 '25 11:11

Ajit Krishna


You can do somethings like this, it worked for me. Use the on appear modifier and call the function setWindowBackgroundColor and pass the color you want the background behind the stack to be.

import SwiftUI

struct ContentView: View {
@State private var isSheetPresented = false

var body: some View {
    VStack {
        Button("Show Sheet") {
            isSheetPresented = true
        }
    }
    .sheet(isPresented: $isSheetPresented) {
        SheetView()
            .onAppear {
                setWindowBackgroundColor(.black) // Set the background color behind the sheet
            }
            .onDisappear {
                setWindowBackgroundColor(.white) // Reset the background color when the sheet is dismissed
            }
    }
}

private func setWindowBackgroundColor(_ color: UIColor) {
    if let window = UIApplication.shared.windows.first {
        window.backgroundColor = color
    }
}
}

struct SheetView: View {
    var body: some View {
        Text("Sheet Content")
            .font(.largeTitle)
            .padding()
            .background(Color.white)
    }
}
like image 23
rifatulislam Avatar answered Nov 02 '25 12:11

rifatulislam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!