我想更改显示在文本中的部分字符串的背景颜色,但我该如何实现?
if let subHeadline = viewModel.createSubHeadlineText() {
Text(subHeadline)
.foregroundColor(Color.black)
.background(!viewModel.isNotSimilar ? Color.yellow: .clear)
}
目前在这段代码中,当条件为真时,整个文本背景都会改变。但我只想更改部分副标题的背景。
您可以使用 AttributeString(如评论中所述)。
struct ContentView: View {
var body: some View {
VStack {
Text(getAttributedString())
}
.padding()
}
func getAttributedString() -> AttributedString {
let string = "This is yellow color"
let attributedString = NSMutableAttributedString(string: string)
attributedString.addAttribute(.backgroundColor, value: UIColor.yellow, range: NSRange(location: 8, length: 6))
return AttributedString(attributedString)
}
}