SwiftUI根据不同条件添加modifier

1个月前 78次点击 来自 iOS

原文地址:Conditional modifier

通过@State变量与条件判断控制:

struct ContentView: View {
    @State private var shouldBeRed: Bool = true

    var body: some View {
        if shouldBeRed {
            Text("Hello, world!")
                .foregroundColor(.red)
        } else {
            Text("Hello, world!")
                .foregroundColor(.blue)
        }
    }
}

使用三元控制符:

struct ContentView: View {
    @State private var shouldBeRed: Bool = true

    var body: some View {
        Text("Hello, world!")
            .foregroundColor(shouldBeRed ? .red : .blue)
    }
}

抽象成View extension 使用:

extension View {
    @ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
}

上述逻辑判断可简化成:

struct ContentView: View {
    @State private var shouldAddShadow: Bool = true

    var body: some View {
        Text("Hello, world!")
            .if(shouldAddShadow) { view in
                view.shadow(color: .black, radius: 10, x: 0.0, y: 0.0)
            }
    }
}
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识,就不会无聊了

要加油~~~

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签