3

I am trying to use a SwiftUI @ViewBuilder to allow users of my package to dynamically specify a view's body content. However, I am trying to restrict the possible views that can be used as an input to just a few default views I implemented (for streamlining purposes).

This is an example:

public protocol PopupBodyView: View { } // every one of my default views conforms to this protocol

func generateChildView(@ViewBuilder items: () -> PopupBodyView)
-> some PopupBodyView {
    return menuItems()
}

If I now call generateChildView, I can correctly specify one view of protocol type PopupBodyView - however, if I specify more than one view in the result builder body, I get the following error:

Instance method 'contextMenu(items:)' requires that 'TupleView<(Text, Text)>' conform to 'PopupBodyView'

extension Text: PopupBodyView { } // add protocol conformance

contextMenu {
    Text("Test")
    Text("Test") // Instance method 'contextMenu(items:)' requires that 'TupleView<(Text, Text)>' conform to 'PopupBodyView'
}

How can I now adapt the default @ViewBuilder to accept only Views that conform to my custom PopupBodyContent type? I basically only want to limit the set of possible inputs the view builder accepts.

linus_hologram
  • 1,595
  • 13
  • 38

0 Answers0