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.

Here's a screenshot from Honk for reference:

And another:

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
}
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With