6

我很好奇您是否可以在 SwiftUI 中创建自定义容器视图。我知道您可以创建自定义内容视图,例如Text(),但不确定您是否可以复制 say 的功能HStack { }

类似于:

HGrid {
    Text("Lorem ipsum")
    Text("Lorem ipsum")
}

然后,自定义容器视图(aka HGrid)将Spacer()在每个添加的组件之间添加。本质上,例如,将其转换为:

HStack {
    Text("Lorem ipsum")
    Spacer()
    Text("Lorem ipsum")
}
4

2 回答 2

8

SwiftUIViewBuilder @functionBuilder

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

也可以看看

于 2019-06-10T18:39:00.350 回答
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()
    }
}
于 2020-09-29T17:39:45.663 回答