SwiftUI SwiftUI Navigation 2 — Questions and Answers
Question 1: How do you present a modal sheet in SwiftUI?
- .modal(isPresented:content:)
- .sheet(isPresented:content:) (Correct answer)
- .present()
- .overlay(isPresented:)
Correct answer: .sheet(isPresented:content:)
The `.sheet(isPresented:content:)` modifier presents a modal sheet when the binding's value becomes true.
Question 2: What is the difference between `.sheet` and `.fullScreenCover` in SwiftUI?
- They are identical
- .fullScreenCover covers the entire screen including the status bar (Correct answer)
- .sheet is only for iPad
- .fullScreenCover cannot be dismissed by the user
Correct answer: .fullScreenCover covers the entire screen including the status bar
`.fullScreenCover` presents a modal that fills the entire screen, while `.sheet` shows a card that can be dismissed by dragging.
Question 3: How can a presented sheet dismiss itself in SwiftUI?
- Call dismiss() on the view
- Use @Environment(\.dismiss) and call dismiss()
- Set isPresented to false directly
- Both B and C work (Correct answer)
Correct answer: Both B and C work
You can dismiss by using `@Environment(\.dismiss)` to call `dismiss()`, or by toggling the `isPresented` binding to `false`.
Question 4: Which SwiftUI modifier presents an alert?
- .alert(isPresented:content:)
- .alert(_:isPresented:actions:)
- Both work (different iOS versions) (Correct answer)
- .dialog(isPresented:)
Correct answer: Both work (different iOS versions)
Both the older `.alert(isPresented:content:)` and the newer `.alert(_:isPresented:actions:)` modifier signatures work depending on the iOS deployment target.
Question 5: What view implements a tab bar in SwiftUI?
- NavigationStack
- TabView (Correct answer)
- PageView
- SegmentedView
Correct answer: TabView
`TabView` renders a tab bar at the bottom and switches between child views based on the selected tab.
Question 6: How do you programmatically select a tab in SwiftUI's `TabView`?
- Call tabView.select(tag:)
- Use `TabView(selection:)` with a binding and `.tag()` on each tab (Correct answer)
- Use @EnvironmentObject to share selection
- Use NavigationStack inside TabView
Correct answer: Use `TabView(selection:)` with a binding and `.tag()` on each tab
Bind a state variable to `TabView(selection:)` and tag each tab view with `.tag()` to enable programmatic tab selection.
How do you present a modal sheet in SwiftUI?