Set a Custom Background for a Modal in SwiftUI
Written by Team Kodeco
In SwiftUI, modals can have customizable backgrounds beyond just the basic colors. You can use images, gradients, shapes and other SwiftUI views as a modal background. This gives you an opportunity to create uniquely styled presentations. In this section, you’ll explore how to set a custom gradient background for a modal.
You will use the presentationBackground
modifier. This modifier automatically fills the entire presentation and allows views behind the presentation to show through translucent areas of the content. Here’s an example:
struct ContentView: View {
@State private var showModal = false
let iceCreamFlavors = [
"Vanilla",
"Chocolate",
"Strawberry",
"Mint Chocolate Chip",
"Cookies and Cream",
"Butter Pecan",
"Pistachio",
"Neapolitan",
"Rocky Road",
"Cookie Dough"
]
var body: some View {
Button("Show Ice Cream Flavors") {
showModal = true
}
.sheet(isPresented: $showModal) {
VStack {
ScrollView(showsIndicators: false) {
ForEach(iceCreamFlavors, id: \.self) { flavor in
Text(flavor)
.font(.title)
.padding()
.background(Color.white.opacity(0.5))
.cornerRadius(10)
.padding(.bottom, 10)
}
}
}
.padding()
.presentationBackground {
LinearGradient(gradient: Gradient(colors: [.pink, .orange, .purple]),
startPoint: .top,
endPoint: .bottom)
}
}
}
}
Tap the Show Ice Cream Flavors button and your preview should look like this:
In this code, you create a Button
that opens a modal when clicked. Inside the modal, you list out a set of ice cream flavors, each displayed in a stylized Text
view. You have a presentationBackground
modifier on the modal that sets the background to a linear gradient of pink, orange and purple.
The presentationBackground
modifier differs from the background
modifier in that it automatically fills the entire presentation and allows views behind the presentation to show through translucent areas of the content.
Remember to experiment and play around with different views and modifiers to achieve your desired look!