如何在SwiftUI中添加自定义容器视图

时间:2019-06-10 18:32:52

标签: swift swiftui xcode11 ios13

我很好奇您是否可以在SwiftUI中创建自定义容器视图。我知道您可以创建自定义内容视图,例如for (i in CancerMet2){ x <- dbGetQuery(mydb, paste('SELECT * FROM kv WHERE Person = ', i, ';')) info = fromJSON(x$info) print(i) } ,但不确定是否可以复制Text()

的功能。

类似于:

HStack { }

然后,自定义容器视图(又名HGrid { Text("Lorem ipsum") Text("Lorem ipsum") } )将在每个添加的组件之间添加HGrid。本质上,例如,将其转换为:

Spacer()

2 个答案:

答案 0 :(得分:3)

SwiftUI通过ViewBuilder @functionBuilder

实现
struct HGrid <Content: View>: View {
    init(@ViewBuilder builder: () -> Content) {
        let content = builder()
        ...
    }
}

另请参见

答案 1 :(得分:0)

如果我们尝试保持简单并只做一件事情,则可以提出两个选择:

import SwiftUI
// Via custom containers
struct HGrid<Content: View>: View {
    let C1: Content
    let C2: Content

    var body: some View {
        HStack {
            C1
            Spacer()
            C2
        }
    }
}
// Via View composition
struct HGridComposition: View {
    var text1: String
    var text2: String

    var body: some View {
        HStack {
            Text(text1)
            Spacer()
            Text(text2)
        }
    }
}


struct ContentView: View {
    var body: some View {
        VStack {
            Text("Composed from Views").font(.headline)
        HGrid(C1: Text("First"), C2: Text("Second"))
            Divider()
            Text("Composed from texts (String)").font(.headline)
        HGridComposition(text1: "Text One", text2: "Text Two")
        }
        .padding([.leading, .trailing])
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}