Compose a background behind your view and extend it beyond the safe area insets.
Technology
SwiftUI
Overview
概要
You can add a view as a background with the background(_:alignment:) view modifier. To add a background under multiple views, or to have a background larger than an existing view, you can layer the views by placing them within a ZStack, and place the view you want to be in the background at the bottom of the view stack. You can specify that a background view should ignore the safe area insets to extend the background to some or all edges.
Add a Background
If your design calls for a background, you can use the background(_:alignment:) modifier to add it underneath an existing view. The following example adds a gradient to the vertical stack using the background(_:alignment:) view modifier:
The background(_:alignment:) view modifier constrains the size of the background view to be the same size as the view to which it’s attached:
Expand the Background Underneath Your View
To create a background that’s larger than the vertical stack, use a different technique. You could add Spacer views above and below the content in the VStack to expand it, but that would also expand the size of the stack, possibly changing it’s layout. To add in a larger background without changing the size of the stack, nest the views within a ZStack to layer the VStack over the background view:
View sizes within a depth stack are independent, unlike when using the background view modifier. The view from Gradient expands to fill the space available to the stack, but avoids the safe area insets by default:
By default, SwiftUI sizes and positions views to avoid system defined safe areas to ensure that system content or the edges of the device won’t obstruct your views. If your design calls for the background to extend to the screen edges, use the ignoresSafeArea(_:edges:) modifier to override the default.
The background gradient fills the display area of the device and ignores the safe area insets.
Adjust Views When Displaying the Keyboard
You can ignore the keyboard’s safe area by adding the ignoresSafeArea(_:edges:) modifier. When you activate the keyboard, the content of the vertical stack remains fixed, ignoring the space used by the keyboard:
To get the contents of the vertical stack to respect the safe areas and adjust to the keyboard, move the modifier to only apply to the background view.
To accommodate the keyboard, SwiftUI resizes and positions your view. Because the background view has the ignoresSafeArea(_:edges:) modifier, it remains unchanged.