colors - 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 的新手,所以不知道如何添加它。
解决方案
这是一个扩展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)
}
}
结果:
您可能需要添加一些额外的代码来处理答案数量与_____
.
推荐阅读
- python - 有没有办法使用 pyspark 动态创建模式信息,而不是在输出 jsonfile 中转义字符?
- python - 数据流作业似乎卡住了
- apache-kafka - 当生产者向不存在的主题发出事件并禁用主题的自动创建时会发生什么?
- jenkins - 如何将多分支项目的队列作业放入队列中?
- c# - 如何将 SQL 的非 Table 字段设置为 Crystal Report 设计和参数
- html - 如何在图像悬停时制作可点击图标
- javascript - 使用javascript将反斜杠url替换为正斜杠url
- c++ - 如何使用 C++ 打印 Pentomino 矩形
- php - 使用 AJAX 向 php 文件发送查询时变量保持为空
- scala - Scala 模式匹配中无法访问的代码