I have overlay with below code
.overlay(abcViewModel.isError ? AnyView(DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
action()
abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))) : AnyView(EmptyView()))
I am trying to avoid use of Anyview and did below code but getting error as "Unknown attribute 'Viewbuilder'" and not sure how to return view in if case
private func getOverlayView() -> some View {
if abcViewModel.isError {
DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
action()
abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))
} else {
return EmptyView()
}
}
Kindly help me the best way for this
You need to add @ViewBuilder
to the computed property/function creating the overlay view.
@ViewBuilder
private var overlay: some View {
if abcViewModel.isError {
DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
action()
abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))
} else {
EmptyView()
}
}
and then pass this property to overlay
.overlay(overlay)
You can add @ViewBuilder
above your function signature like:
@ViewBuilder private func createOverlay() -> some View { ... }
And get rid of all return
keywords.
You can extend the View
and define a simple function and hide any view conditionally like:
extension View {
@ViewBuilder
func hidden(if condition: Bool) -> some View {
if condition { self.hidden() }
else { self }
}
}
and use it like:
DialogBoxOneButton(...)
.hidden(if: !abcViewModel.isError)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.