我正在尝试创建一个自定义 SwiftUI 视图,可以使用 aLocalizedStringKey
或StringProtocol
就像内置 SwiftUI 一样进行初始化Button
。好处是我可以使用自动本地化的字符串或假定已本地化的参数来初始化自定义视图。
苹果在这里描述了这种用法:
作为一般规则,当您需要本地化时,请使用字符串文字参数;当您不需要本地化时,请使用字符串变量参数。
来源:https://developer.apple.com/documentation/swiftui/localizedstringkey
这是我的代码:
import SwiftUI
struct CustomView<Content: View>: View {
private let title: String
@ViewBuilder let content: Content
init(_ titleKey: LocalizedStringKey, @ViewBuilder content: () -> Content) {
self.title = ???
self.content = content()
}
init<S>(_ title: S, @ViewBuilder content: () -> Content) where S : StringProtocol {
self.title = ???
self.content = content()
}
var body: some View {
ZStack {
Color.green
Text(self.title)
}
}
}
在这两个初始化程序中都不清楚我应该如何设置title
在body
.
我认为苹果在这里使用了某种模式,但目前还不清楚如何实现这一点。
我意识到我可以在自定义视图中存储两个变量;一个用于 ,LocalizedStringKey
另一个用于String
,然后有一个在 中使用适当输入类型的开关body
。但这似乎比我预期的工作量要多一些。
任何帮助表示赞赏。