【问题标题】:Multiple colors for typed words in TextField in SwiftUISwiftUI 中 TextField 中键入单词的多种颜色
【发布时间】:2020-07-11 10:52:05
【问题描述】:

如果是文字我会写

Text("Hello ")+Text("world").foregroundColor(.yellow)

我可以在TextField / TextEditor 中做什么?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    我发现了一个可怕的 SwiftUI 解决方案:

    @State private var text = "Hello world"
    
    var body: some View {
        VStack {
            ZStack(alignment: .topLeading) {
                
                TextEditor(text: $text)
                    .foregroundColor(.clear)
                
                text
                    .split(separator: " ")
                    .map {
                        if $0 == "world" {
                            return Text($0 + " ").foregroundColor(.red)
                        } else {
                            return Text($0 + " ")
                        }
                    }
                    .reduce(Text(""), +)
                    .padding(.vertical, 8.5)
                    .padding(.horizontal, 5)
            }
        }.padding()
    }
    

    这种方法的问题:

    1. TextEditor 中的文本有一个填充
    2. TextEditor 的背景默认是白色的,所以我不得不将它在 ZStack 中向下移动,从而禁用在文本编辑器中触摸 Text 的可能性

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 2020-10-19
    • 2020-08-03
    • 1970-01-01
    • 2014-09-13
    • 2012-01-12
    • 1970-01-01
    • 2016-02-23
    相关资源
    最近更新 更多