Show a popover on iPhone in SwiftUI
In SwiftUI, we can use the popover() modifier to present a popover when a given condition is true. By default, it shows a popover on iPad in a regular horizontal size class but turns into a sheet on iPhone.
Starting with iOS 16.4, we can use the presentationCompactAdaptation(_:) modifier to tell SwiftUI that we prefer popover presentation even in compact size classes. This modifier is applied to the view inside the popover's content.
Here’s an example of how we can show a popover for a list of ingredients in a recipe app when the user clicks on the list button:
IngredientsListButton(
showIngredients: $showIngredients
)
.popover(isPresented: $showIngredients) {
IngredientsList(
ingredients: recipe.ingredients
)
.presentationCompactAdaptation(.popover)
}
Since we indicated that we prefer a popover for compact adaptation, SwiftUI will show a popover instead of a sheet, even on a phone.
If you have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.