I\'m implementing a very custom NavigationLink called MenuItem
and would like to reuse it across the project. It\'s a struct that conforms to Vie
The way Apple does it is using function builders. There is a predefined one called ViewBuilder
. Make it the last argument, or only argument, of your init
method for MenuItem
, like so:
..., @ViewBuilder builder: @escaping () -> Content)
Assign it to a property defined something like this:
let viewBuilder: () -> Content
Then, where you want to diplay your passed-in views, just call the function like this:
HStack {
viewBuilder()
}
You will be able to use your new view like this:
MenuItem {
Image("myImage")
Text("My Text")
}
This will let you pass up to 10 views and use if
conditions etc. though if you want it to be more restrictive you will have to define your own function builder. I haven't done that so you will have to google that.