Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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.

Use the frame modifier to make a full-screen button.
Use the frame modifier to make a full-screen button.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.