jaywcjlove / swiftui-example

SwiftUI 示例,技巧和技术集合,帮助我构建应用程序,解决问题以及了解SwiftUI的实际工作方式。
https://jaywcjlove.github.io/swiftui-example
MIT License
491 stars 38 forks source link

如何将一个View 作为变量传递给另一个View struct #5

Open jaywcjlove opened 3 years ago

jaywcjlove commented 3 years ago

https://stackoverflow.com/a/63937440/1334703

struct ContainerView<Content: View>: View {
    let content: Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content()
    }

    var body: some View {
        content
    }
}

这不仅允许您将简单的Views放入其中,而且由于使用@ViewBuilder,还可以使用if-else和switch-case块:

使用示例 1:

struct SimpleView: View {
    var body: some View {
        ContainerView {
            Text("SimpleView Text")
        }
    }
}

使用示例 2:

struct IfElseView: View {
    var flag = true

    var body: some View {
        ContainerView {
            if flag {
                Text("True text")
            } else {
                Text("False text")
            }
        }
    }
}

使用示例 3:

struct SwitchCaseView: View {
    var condition = 1

    var body: some View {
        ContainerView {
            switch condition {
            case 1:
                Text("One")
            case 2:
                Text("Two")
            default:
                Text("Default")
            }
        }
    }
}

如果您想要一个贪婪的容器,它将占用所有可能的空间(与上面的容器只声明其子视图所需的空间相反),这里是:

struct GreedyContainerView<Content: View>: View {
    let content: Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content()
    }

    var body: some View {
        Color.clear
            .overlay(content)
    }
}