Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Popover in SwiftUI
Written by Team Kodeco

In SwiftUI, a popover is a small window that overlays the current view to display content. Popovers are often used in iPad apps to present additional information or options. In this cookbook entry, you’ll learn how to create a popover in SwiftUI.

Creating a popover in SwiftUI requires using the popover modifier on a view. Here’s an example that uses attachmentAnchor to anchor the popover to the top leading edge of the button:

struct ContentView: View {
  @State private var showPopover = false

  var body: some View {
    Button("Show Popover") {
      showPopover.toggle()
    }
    .buttonStyle(.borderedProminent)
    .popover(isPresented: $showPopover,
             attachmentAnchor: .point(.topLeading),
             content: {
      Text("This is a Popover")
        .padding()
        .frame(minWidth: 300, maxHeight: 400)
        .background(.red)
        .presentationCompactAdaptation(.popover)
    })
  }
}

Tap the Show Popover button and your preview should look like this:

A Popover in SwiftUI.
A Popover in SwiftUI.

In this example, a button with a prominent bordered style toggles the showPopover state variable when pressed. The popover modifier is then applied on the button to show the popover when showPopover is true.

This modifier accepts several parameters: isPresented, attachmentAnchor and content.

  • isPresented is a binding to a Boolean value that determines whether to show the popover.
  • attachmentAnchor sets the anchor point for the popover. Here, .point(.topLeading) anchors the popover to the top leading point of the button.
  • content is a closure that returns the view to be displayed in the popover. In this case, the popover content is adapted to use a popover presentation style when in a compact environment.

The content of the popover can be any SwiftUI view, including custom views. You can also use stack views, such as VStack, HStack and ZStack, to create more complex layouts.

To dismiss the popover, users can tap outside of it, or you can programmatically dismiss it by setting the isPresented binding to false.

With this code, you’ve now created a customized popover in SwiftUI. Feel free to experiment with different layouts and contents to create your own popovers.

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.