1

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

ragavanmonke
  • 409
  • 3
  • 13
  • This should be helpful [How to access own window within SwiftUI view?](https://stackoverflow.com/a/60359809/12299030) – Asperi Aug 20 '22 at 06:09

1 Answers1

0

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)
    }
}
  • This is fantastic, thank you so much (and sorry to only see it now). This is exactly what I was looking for. Just a heads up, when I added that function, I got a build warning that says: `'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead` Is this something that would be blocked by review? How would we make this error go away? FWIW I tried ChatGPT for this, and it couldn't figure out a solution that worked (kept giving me broken code). – ragavanmonke Aug 01 '23 at 17:44