Home > Net >  SwiftUI - apply modifier in case of version of macOS is some specific
SwiftUI - apply modifier in case of version of macOS is some specific

Time:10-31

There is an ability to run code related to version of OS:

if #available(macOS 11.0, *) {
    Button("test", action: {})
         //.modifier1
         //.modifier2
         //.modifier3
         //.modifier4
         //.modifier5
         //.modifier6
         //.modifier7
         //.modifier8
         .foreground(.red)
} else {
    Button("test", action: {})
         //.modifier1
         //.modifier2
         //.modifier3
         //.modifier4
         //.modifier5
         //.modifier6
         //.modifier7
         //.modifier8
}

Is it possible to do the same on single modifier without duplication of code?

Sth like syntax:

Button("test", action: {})
     //.modifier1
     //.modifier2
     //.modifier3
     //.modifier4
     //.modifier5
     //.modifier6
     //.modifier7
     //.modifier8
    .if(macOS 11.0, *) { $0.foreground(.red) }

?

CodePudding user response:

Here is what you are looking for:

struct ContentView: View {
    
    var macOS_11: Bool {
        if #available(macOS 11.0, *) { return true }
        else { return false }
    }
    
    var body: some View {
        
        Text("Hello, World!")
            .foregroundColor(macOS_11 ? .red : nil)
        
    }
    
}

CodePudding user response:

You could try something like this:

struct ContentView: View {
    let macOS11Available: Bool
    
    init() {
        if #available(macOS 11, *) {
            self.macOS11Available = true
        } else {
            self.macOS11Available = false
        }
    }
    
    var body: some View {
        VStack (spacing: 77) {
            Button("test modifier", action: {})
                .foregroundColor(macOS11Available ? .red : .green)
            //.modifier1
            //.modifier2
            //.modifier3
            //.modifier4
            //.modifier5
            //.modifier6
            //.modifier7
            //.modifier8
            
        }.frame(width: 444, height: 444)
    }
}

CodePudding user response:

Solution based on idea of swiftPunk

public class MacOsVer {
    static var higherThan_11: Bool {
        if #available(macOS 11.0, *) { return true }
        else { return false }
    }
    
    static var higherThan_11_3: Bool {
        if #available(macOS 11.3, *) { return true }
        else { return false }
    }
    
    static var higherThan_12: Bool {
        if #available(macOS 12, *) { return true }
        else { return false }
    }
}

So with if modifier ( https://prnt.sc/1xx7pir )

I can do sth like:

Text("some Text")
    .bacground(.blue)
    .if(MacOsVer.higherThan_11) { $0.foregroundColor(.Red) }
  • Related