问题描述
我有一段文字正在使用.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)
}
}
结果:
您可能想添加一些额外的代码来处理答案数量与_____
的出现不匹配的情况。