skip to Main Content

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

2

Answers


  1. 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)
    
    Login or Signup to reply.
  2. You can add @ViewBuilder above your function signature like:

    @ViewBuilder private func createOverlay() -> some View { ... }
    

    And get rid of all return keywords.


    💡 Cleaner method

    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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search