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

后端 未结 6 1050
孤城傲影
孤城傲影 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:41

    To sum up everything I read here and the solution which worked for me and on iOS14:

    struct ContainerView: View {
        let content: Content
    
        init(@ViewBuilder content: @escaping () -> Content) {
            self.content = content()
        }
        
        var body: some View {
            content
        }
    }
    

    This not only allows you to put simple Views inside, but also, thanks to @ViewBuilder, use if-else and switch-case blocks:

    struct SimpleView: View {
        var body: some View {
            ContainerView {
                Text("SimpleView Text")
            }
        }
    }
    
    struct IfElseView: View {
        var flag = true
        
        var body: some View {
            ContainerView {
                if flag {
                    Text("True text")
                } else {
                    Text("False text")
                }
            }
        }
    }
    
    struct SwitchCaseView: View {
        var condition = 1
        
        var body: some View {
            ContainerView {
                switch condition {
                case 1:
                    Text("One")
                case 2:
                    Text("Two")
                default:
                    Text("Default")
                }
            }
        }
    }
    

    Bonus: If you want a greedy container, which will claim all the possible space (in contrary to the container above which claims only the space needed for its subviews) here's it:

    struct GreedyContainerView: View {
        let content: Content
    
        init(@ViewBuilder content: @escaping () -> Content) {
            self.content = content()
        }
        
        var body: some View {
            Color.clear
                .overlay(content)
        }
    }
    

提交回复
热议问题