如何使用仅适用于 iOS 14+ 且部署目标为 iOS 13 的视图修饰符 [英] How to use view modifiers only available for iOS 14+ with deployment target of iOS 13
问题描述
当视图仅在 iOS 14 上可用但您的应用可用于 iOS 13 时,如何向视图添加视图修饰符?
How can you add a view modifier to a view when it's only available on iOS 14 but your app is available for iOS 13?
例如,textCase(_)
.iOS 14 中的部分标题是大写的,因此要使用标题文本的大小写,您应该在 Text
上设置 .textCase(.none)
,但这直到iOS 14.
For an example, textCase(_)
. Section headers in iOS 14 are uppercase so to use the case of your header text you should set .textCase(.none)
on your Text
, but this didn't exist until iOS 14.
Section(header:
Text("Header")
.textCase(.none) //FIXME: 'textCase' is only available in iOS 14.0 or newer
.font(.system(size: 14, weight: .bold))
.foregroundColor(.secondary)
.padding(.top, 50)
)
Xcode 提供了一些建议:
Xcode offers some suggestions:
- 添加 if #available 版本检查
- 添加@available 属性
如果您使用#available 版本检查,它会使用#available 包装所有范围内的代码,因此您必须复制所有这些以添加一行代码.如果使用@available,则必须复制整个 body 属性或整个结构.
If you use the #available version check, it wraps all of that scoped code with #available, so you'd have to duplicate all of that to add that one line of code. If you use @available you have to duplicate the entire body property or entire struct.
我考虑过创建我自己的 ViewModifier,它只会在 iOS 14 时应用它,但这会导致这个可怕的错误:
I considered creating my own ViewModifier that would only apply it if iOS 14 but that gives this dreaded error:
函数声明了一个不透明的返回类型,但返回语句在它的主体没有匹配的底层类型
Function declares an opaque return type, but the return statements in its body do not have matching underlying types
struct CompatibleTextCaseModifier: ViewModifier {
func body(content: Content) -> some View {
if #available(iOS 14.0, *) {
return content
.textCase(.none)
} else {
return content
}
}
}
推荐答案
Mark body
为 @ViewBuilder
- 这将允许自动跟踪内部不同的返回类型,并删除 return
因为显式返回禁用了视图构建器包装器.
Mark body
as @ViewBuilder
- this will allow track internal different return types automatically, and remove return
because explicit return disables view builder wrapper.
所以这里是固定变体
struct CompatibleTextCaseModifier: ViewModifier {
@ViewBuilder
func body(content: Content) -> some View {
if #available(iOS 14.0, *) {
content
.textCase(.none)
} else {
content
}
}
}
和用法
Section(header:
Text("Header")
.modifier(CompatibleTextCaseModifier())
.font(.system(size: 14, weight: .bold))
.foregroundColor(.secondary)
.padding(.top, 50)
) {
Text("test")
}
这篇关于如何使用仅适用于 iOS 14+ 且部署目标为 iOS 13 的视图修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!