微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI:在同一Text视图中使用不同的颜色

如何解决SwiftUI:在同一Text视图中使用不同的颜色

我有一段文字正在使用.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的新手,所以不确定如何添加这个。

Image 1

解决方法

这是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)
    }
}

结果:

enter image description here

您可能想添加一些额外的代码来处理答案数量与_____的出现不匹配的情况。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。