当视图修改器仅在iOS 14上可用但您的应用程序在iOS 13上可用时,如何向视图添加视图修改器?
例如,textCase(_)
。 iOS 14中的节标题是大写的,因此要使用标题文本的大小写,应在.textCase(.none)
上设置Text
,但这直到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提供了一些建议:
如果使用#available版本检查,它将用#available包装所有范围内的代码,因此您必须重复所有这些操作才能添加一行代码。如果使用@available,则必须复制整个body属性或整个struct。
我考虑过创建自己的ViewModifier,该ViewModifier仅在iOS 14上适用,但会出现此可怕的错误:
函数声明了不透明的返回类型,但是return语句在 它的主体没有匹配的基础类型
struct CompatibleTextCaseModifier: ViewModifier {
func body(content: Content) -> some View {
if #available(iOS 14.0, *) {
return content
.textCase(.none)
} else {
return content
}
}
}
答案 0 :(得分:4)
将body
标记为@ViewBuilder
-这将允许自动跟踪内部不同的返回类型,并删除return
,因为显式返回会禁用视图构建器包装。
所以这是固定的变体
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")
}