如何应用修饰符或按条件查看

And*_*rew 3 swiftui

@State var modifierEnabled : Bool

struct BlankModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
    }
}

extension View {
    func TestModifierView() -> some View{
       return self.modifier(BlankModifier())
    }
}
Run Code Online (Sandbox Code Playgroud)

TestModifierView仅在以下情况下如何申请modifierEnabled == true

And*_*rew 10

@available(OSX 11.0, *)
public extension View {
    @ViewBuilder
    func `if`<Content: View>(_ condition: Bool, content: (Self) -> Content) -> some View {
        if condition {
            content(self)
        } else {
            self
        }
    }
}

@available(OSX 11.0, *)
public extension View {
    @ViewBuilder
    func `if`<TrueContent: View, FalseContent: View>(_ condition: Bool, ifTrue trueContent: (Self) -> TrueContent, else falseContent: (Self) -> FalseContent) -> some View {
        if condition {
            trueContent(self)
        } else {
            falseContent(self)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例(一个修饰符):

Text("some Text")
   .if(modifierEnabled) { $0.foregroundColor(.Red) }
Run Code Online (Sandbox Code Playgroud)

用法示例2(与条件相关的两个修饰符链):

Text("some Text")
   .if(modifierEnabled) { $0.foregroundColor(.red) } 
   else:                { $0.foregroundColor(.red).background(Color.blue) }
Run Code Online (Sandbox Code Playgroud)

但!!!!!!!!!!!

重要的是,此修饰符可能是某些身份问题的原因。(稍后你会明白这一点)

所以在某些情况下最好使用标准if结构