【问题标题】:SwiftUI: Use of different colours within same Text viewSwiftUI:在同一个文本视图中使用不同的颜色
【发布时间】:2020-08-29 20:38:05
【问题描述】:

我在一段文本中使用 .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

【问题讨论】:

  • 这能回答你的问题吗? How to use Attributed String in SwiftUI
  • 您可以使用不同的修饰符加入Text。例如,您可以使用Text("Hello").foregroundColor(.red) + Text("World").foregroundColor(.blue)

标签: colors swiftui


【解决方案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)
    }
}

结果:

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

【讨论】:

    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 2012-03-22
    • 2013-10-19
    • 2022-07-02
    • 2014-04-03
    • 2013-02-13
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多