代码之家  ›  专栏  ›  技术社区  ›  Hudi Ilfeld

SwiftUI:组合自定义文本

  •  -1
  • Hudi Ilfeld  · 技术社区  · 3 年前

    SwiftUI 内置的 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 但编译器也不喜欢这样。

    我该如何巧妙地实现这一点?

    0 回复  |  直到 3 年前
        1
  •  0
  •   magnuskahr    3 年前

    这是的自定义功能 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)
        }
    }
    

    然而,这更多的是一种概念证明,而不是一种实践建议。