首页 > 解决方案 > SwiftUI:在同一个文本视图中使用不同的颜色

问题描述

我有一段文本,我正在使用 .replacingOccurrences 在问题句中显示用户的答案:

           Text((question.text)
                .replacingOccurrences(of: "_____", with:
                    question.answers[question.userAnswer]
                ))
                .font(Font.custom("ClearSans-Bold", size: 18))
                .foregroundColor(.black )
                .padding(.bottom, 20)
                .multilineTextAlignment(.center)

我希望用户的答案question.answers[question.userAnswer]与正文的颜色(红色/绿色)不同(类似于附加图像),但是我是 SwiftUI 的新手,所以不知道如何添加它。

图 1

标签: colorsswiftui

解决方案


这是一个扩展String,它几乎可以满足您的需求:

extension String {
    func replacingOccurrences(of: String, with: [Text]) -> Text {
        return self.components(separatedBy: of).enumerated().map({(i, s) in
            return i < with.count ? Text(s) + with[i] : Text(s)
        }).reduce(Text(""), { (r, t) in
            return r + t
        })
    }
}

它使用 George_E 建议的 Text 元素的串联。你可以像这样使用它:

struct ContentView: View {

    let question: String = "The witch found the concoction extremely _____. _____ makes better ones."

    let answers: [String] = ["nauseate", "A friend of her's"]

    var body: some View {
        question.replacingOccurrences(of: "_____", with: self.answers.map({s in Text(s).foregroundColor(.red)})).foregroundColor(.secondary)
    }
}

结果:

在此处输入图像描述

您可能需要添加一些额外的代码来处理答案数量与_____.


推荐阅读