首页 > 解决方案 > 如何使用 ViewModifier 在 swiftUI 中选择性地设置前景色以查看

问题描述

我有一个图像视图,基于一个布尔值,我应该使用色调,如果条件为真,我应该使用色调,否则我应该使用原始图像,我尝试了多种方式使用 ViewModifier,但我找不到解决方案。是否有可能使用 ViewModifier 获得预期的结果?

struct ViewColor: ViewModifier {
    var tint: Bool
    
    func body(content: Content) -> some View {
        Group {
            if self.tint {
                content.foregroundColor(Color("colorText"))
            }else
            {
              //  content.foregroundColor(Color("colorAccent"))
    
            }
        }
            
        }
    }

标签: iosswiftui

解决方案


这是一个解决方案(使用 Xcode 12b 测试)

struct ViewColor: ViewModifier {
    var tint: Bool

    @ViewBuilder
    func body(content: Content) -> some View {
        if self.tint {
            content.foregroundColor(Color("colorText"))
        } else {
            content
        }
    }
}

推荐阅读