[SwiftUI 知识碎片] Debris-14 视图构成

249 阅读1分钟
更多内容欢迎关注公众号 「Swift花园」
SwiftUI 允许我们把复杂视图拆解成一些小视图,而不会影响到性能。这意味着我们可以一个大视图分割成多个更小的视图,而 SwiftUI 负责为我们组装。

举个例子,下面这个视图中,我们用一种特别的方法样式化文本视图 —— 它们有大字号,一些 padding ,前景色和背景色,以及胶囊的形状。

struct ContentView: View {
    var body: some View {
        VStack(spacing: 10) {
            Text("First")
                .font(.largeTitle)
                .padding()
                .foregroundColor(.white)
                .background(Color.blue)
                .clipShape(Capsule())

            Text("Second")
                .font(.largeTitle)
                .padding()
                .foregroundColor(.white)
                .background(Color.blue)
                .clipShape(Capsule())
        }
    }
}

因为这两个文本视图除了文本的部分都是一样的,我们可以用一个新的自定义视图来封装它们,像下面这样:

struct CapsuleText: View {
    var text: String

    var body: some View {
        Text(text)
            .font(.largeTitle)
            .padding()
            .foregroundColor(.white)
            .background(Color.blue)
            .clipShape(Capsule())
    }
}

然后在原始视图中使用 CapsuleText 视图,就像这样:

struct ContentView: View {
    var body: some View {
        VStack(spacing: 10) {
            CapsuleText(text: "First")
            CapsuleText(text: "Second")
        }
    }
}

当然,我们也可以在属性中存储一些 modifier ,然后在使用时再自定义。举个例子,如果我们把 foregroundColorCapsuleText 中移除,可以在创建实例时再应用这个 modifier:

VStack(spacing: 10) {
    CapsuleText(text: "First")
        .foregroundColor(.white)
    CapsuleText(text: "Second")
        .foregroundColor(.yellow)
}


我的公众号 这里有Swift及计算机编程的相关文章,以及优秀国外文章翻译,欢迎关注~