更改文本中字符串部分的背景颜色

问题描述 投票:0回答:1

我想更改显示在文本中的部分字符串的背景颜色,但我该如何实现?

if let subHeadline = viewModel.createSubHeadlineText() { 
  Text(subHeadline)
    .foregroundColor(Color.black)
    .background(!viewModel.isNotSimilar ? Color.yellow: .clear)
}

目前在这段代码中,当条件为真时,整个文本背景都会改变。但我只想更改部分副标题的背景。

ios xcode swiftui
1个回答
0
投票

您可以使用 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)
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.