SwiftUI: Conditionally Showing NavigationItem and ToolbarItem

.toolbar {
if viewModel.showPreviousButton {
ToolbarItem(placement: .navigationBarLeading) {
Button("previous", action: viewModel.previous)
} // Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder'
}
}
var body: some View {
VStack {
/// the contents of your view
}
.toolbar {
ItemsToolbar(
next: viewModel.next,
previous: viewModel.previous,
skip: skip,
close: skip,
nextButton: viewModel.showRightBarButton,
showPrevious: viewModel.showPreviousButton
)
}
struct ItemsToolbar: ToolbarContent {
let next: () -> Void
let previous: () -> Void
let skip: () -> Void
let close: () -> Void
let nextButton: OnboardingScreenViewModel.RightBarButton
let showPrevious: Bool
var body: some ToolbarContent {
ToolbarItemGroup(placement: .navigationBarLeading) {
if showPrevious {
Button(
"Previous",
action: previous
)
}
}
ToolbarItemGroup(placement: .navigationBarTrailing) {
switch nextButton {
case .close:
Button(
"Close",
action: close
)
case .skip:
Button(
"Next",
action: next
)
Button(
"Skip",
action: skip
)
case .none:
EmptyView()
}
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store