Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jaywcjlove opened this issue Apr 23, 2021 · 0 comments
Open

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

jaywcjlove opened this issue Apr 23, 2021 · 0 comments
Labels

Comments

@jaywcjlove
Copy link
Owner

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)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant