可以運行與作業系統版本相關的代碼:
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
}
是否可以在不重復代碼的情況下對單個修飾符執行相同操作?
類似的語法:
Button("test", action: {})
//.modifier1
//.modifier2
//.modifier3
//.modifier4
//.modifier5
//.modifier6
//.modifier7
//.modifier8
.if(macOS 11.0, *) { $0.foreground(.red) }
?
uj5u.com熱心網友回復:
這是您要尋找的內容:
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)
}
}
2.0.0 版:
這是更好的方法:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, World!")
.foregroundColor(MacOsVer.shared.higherThan_11 ? .red : nil)
Text("Hello, World!")
.foregroundColor(MacOsVer.shared.higherThan_11_3 ? .red : nil)
Text("Hello, World!")
.foregroundColor(MacOsVer.shared.higherThan_12 ? .red : nil)
}
.frame(width: 200)
.padding()
}
}
public class MacOsVer {
let higherThan_11: Bool
let higherThan_11_3: Bool
let higherThan_12: Bool
init() {
if #available(macOS 11.0, *) { higherThan_11 = true }
else { higherThan_11 = false }
if #available(macOS 11.3, *) { higherThan_11_3 = true }
else { higherThan_11_3 = false }
if #available(macOS 12, *) { higherThan_12 = true }
else { higherThan_12 = false }
}
static let shared: MacOsVer = MacOsVer()
}
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
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)
}
}
uj5u.com熱心網友回復:
基于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 }
}
}
所以使用 if 修飾符(https://prnt.sc/1xx7pir)
我可以這樣做:
Text("some Text")
.bacground(.blue)
.if(MacOsVer.higherThan_11) { $0.foregroundColor(.Red) }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342720.html
上一篇:zsh:找不到命令:php
