使用内置的SwiftUI
Text
,如果我们想创建富文本,我们可以连接多个Text
视图
像这样:
Text("hello").foregroundColor(.white) + Text("world").foregroundColor(.pink)
但是,如果我有一个自定义文本:
struct MyText: View {
let label: String
var body: some View {
Text(self.label)
.foregroundColor(.myAppColor)
}
}
然后组合:
MyText(label: "hello") + MyText(label: "world")
编译器输出以下错误:
Referencing operator function '+' on 'FloatingPoint' requires that 'MyText' conform to 'FloatingPoint'
我尝试将MyText
强制转换为Text,但编译器也不喜欢这样。
我该如何以一种巧妙的方式实现这一点?
这是Text
的自定义功能,但您可以模仿一些行为。参见以下示例:
import SwiftUI
struct MyText: View {
private let configurations: [Configuration]
init(_ title: String, foregroundColor: Color = .black) {
self.configurations = [
.init(title: title,
foregroundColor: foregroundColor)
]
}
private init(configurations: [Configuration]) {
self.configurations = configurations
}
private struct Configuration: Identifiable {
let id = UUID()
let title: String
let foregroundColor: Color
}
var body: some View {
HStack {
ForEach(configurations, content: Render.init)
}
}
static func + (lhs: Self, rhs: Self) -> Self {
let configurations = lhs.configurations + rhs.configurations
return MyText(configurations: configurations)
}
private struct Render: View {
let configuration: Configuration
var body: some View {
Text(configuration.title)
.foregroundColor(configuration.foregroundColor)
}
}
}
struct MyText_Previews: PreviewProvider {
static var previews: some View {
MyText("hej") + MyText("Yo", foregroundColor: .red)
}
}
然而,这更多的是一种概念的证明,而不是一种实践的建议。