提问者:小点点

如何在swiftUI中使用ViewModifier可选地设置前景颜色以查看


我有一个图像视图,基于一个布尔值我应该使用淡色,如果条件为真我应该使用淡色,否则我应该使用原始图像,我尝试了很多方法使用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"))
    
            }
        }
            
        }
    }

共2个答案

匿名用户

下面是一个解决方案(用Xcode 12b测试)

struct ViewColor: ViewModifier {
    var tint: Bool

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

匿名用户

我在按钮里面用了图像。 为了在按钮内保持图像的原始颜色,我们应该使用renderingmode(.origination)对图像进行着色,我们应该使用renderingmode(.template),对于我的场景,我应该使用条件运算符来得到精确的结果,下面是代码

 struct ButtonIconView: View {
    var icon : String
    var tint : Bool = true
    var body: some View {
        Button(action: {
            print("Button action")
            
        }){
            Image(icon)
                .renderingMode(self.tint ? .template : .original) // To get the original image color we should use .original in rendering mode to tint image we should use .template
                .resizable().scaledToFit() .modifier(ViewColor(tint: self.tint)).frame(width: 18, height: 18)
        }.frame(width: 54, height:48)
    }
}

要使用ViewModifier添加和删除浅色,我们应该遵循@Asperi的答案

struct ViewColor: ViewModifier {
    var tint: Bool

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