Create a Full-Screen Button in SwiftUI
Written by Team Kodeco
Full-screen buttons provide an easy and convenient way to allow users to perform actions that require their full attention. In SwiftUI, creating a full-screen button is a breeze. Here’s how:
struct ContentView: View {
var body: some View {
FullScreenButtonView()
}
}
struct FullScreenButtonView: View {
var body: some View {
Button(action: {
print("Full Screen Button Tapped")
}, label: {
Text("Full Screen Button")
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
}
}
Your preview should look like this. Tap anywhere on the screen and you should see the button flash like it’s just been tapped.
Note: To see the console output, you’ll need to run this example in a simulator.
In the example above, you define a SwiftUI view that contains a full-screen button. The button has a plain text label that reads “Full Screen Button” and an action that prints a message to the console when tapped.
To make the button full-screen, you add a modifier .frame(maxWidth: .infinity, maxHeight: .infinity)
to the button. This modifier tells SwiftUI to expand the button horizontally and vertically as much as possible, effectively making it a full-screen button.
You can customize the appearance of the full-screen button just like any other SwiftUI button. You can add images, icons and even complex views to the button, and they will all be scaled to fit the full-screen size.
Full-screen buttons are especially useful for actions that require the user’s full attention or confirmations for important actions. They make it easy for users to focus on the message and take the appropriate action without distraction.