如何在 SwiftUI 中根据操作系统版本设置条件修饰符?

Tra*_*nos 3 ios swift swiftui

我是编程新手,今天加入了 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)
}
Run Code Online (Sandbox Code Playgroud)

我学到的第一件事就是不要重复相同的代码,但是如何在不重复代码的情况下轻松应用不同的修饰符?像这样的东西:

Text("Hello World")
    .font(.title.bold())
    .multilineTextAlignment(.leading)

  if #available(iOS 17.0, *) {
    .foregroundStyle(.red)
  } else {
    .foregroundColor(.red)
  }
Run Code Online (Sandbox Code Playgroud)

PS:我见过这样的帖子来实现一个以 bool 作为输入的自定义修饰符,但它不能以编译器可以理解的方式获取操作系统版本,例如#available(iOS 17.0, *).

更新

我知道我们可以实现类似的操作系统检查,如下所示,但我正在以相同的通用方式寻找版本检查:

Text("Hello World")
    .font(.title.bold())
    .multilineTextAlignment(.leading)

  #if os(iOS)
    .foregroundStyle(.red)
  #else
    .foregroundColor(.red)
Run Code Online (Sandbox Code Playgroud)

感谢您考虑我的问题

Moj*_*ini 5

您可以通过简单的扩展来实现非常相似的目标:

extension View {
    func apply<V: View>(@ViewBuilder _ block: (Self) -> V) -> V { block(self) }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样使用它:

Text("Hello World")
    .font(.title.bold())
    .multilineTextAlignment(.leading)
    .apply {
        if #available(iOS 15.0, *) {
            $0.foregroundStyle(.red)
        } else {
            $0.foregroundColor(.red)
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,您可以apply对任何您喜欢的视图进行任何修改,并且正如您所要求的那样,它非常通用。