Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply modifier or view by condition

Tags:

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())
    }
}

How to apply TestModifierView only in case of modifierEnabled == true ?

like image 448
Andrew Avatar asked Dec 18 '22 15:12

Andrew


1 Answers

@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)
        }
    }
}

usage example ( one modifier ) :

Text("some Text")
   .if(modifierEnabled) { $0.foregroundColor(.Red) }

usage example2 (two modifier chains related to condition) :

Text("some Text")
   .if(modifierEnabled) { $0.foregroundColor(.red) } 
   else:                { $0.foregroundColor(.blue).background(Color.green) }

BUT!!!!!!!!!!!

Important thing that this modifier can be reason of some indentity issues. (later you will understand this)

So in some cases better to use standard if construction

like image 115
Andrew Avatar answered Jan 12 '23 16:01

Andrew