How to pass one SwiftUI View as a variable to another View struct

后端 未结 6 1046
孤城傲影
孤城傲影 2020-12-30 19:24

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

6条回答
  •  执笔经年
    2020-12-30 19:58

    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.

提交回复
热议问题