我是编程新手,今天我加入了StackOverflow.我希望我能根据指导方针提出以下问题:
我正在启动SwiftUI,它似乎有许多只能在iOS 17上运行的代码,看看这个:
if #available(iOS 17.0, *) {
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
// This modifier only works on iOS 17
.foregroundStyle(.red)
} else {
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
.foregroundColor(.red)
}
我学到的第一件事是不要重复相同的代码,但我如何才能在不重复代码的情况下轻松地应用不同的修饰符?大概是这样的:
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
if #available(iOS 17.0, *) {
.foregroundStyle(.red)
} else {
.foregroundColor(.red)
}
附注:我见过posts like this实现了一个自定义修饰符,该修饰符接受bool作为输入,但它不能以编译器理解的方式接受操作系统版本.
Update
我知道我们可以为操作系统判断实现类似的结果,如下所示,但我正在以相同的一般方式寻找版本判断:
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
#if os(iOS)
.foregroundStyle(.red)
#else
.foregroundColor(.red)
谢谢你考虑我的问题