首页 > 解决方案 > 如何使用 swift 为 Xcode 中的特定文本添加颜色?

问题描述

我在通过在 Xcode 中进行 API 调用收到的字符串末尾附加了一个文本。现在,我想添加颜色并仅将“点击阅读更多”文本加粗。关于如何实现这一目标的任何建议?感谢您的帮助:)

self.content[i] = recievedData.title! + "\nTap to Read More "

let str = "Tap to Read More"
    
    let attributes: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.red,
    ]

    let attributedQuote = NSAttributedString(string: str, attributes: attributes)

标签: iosswiftxcode

解决方案


你可以试试NSAttributedString

例子:

let str = "Tap to Read More"

// Create your attributed string
let attributes: [NSAttributedString.Key : Any] = [.foregroundColor : UIColor.red]
let attributedStr = NSAttributedString(string: str, attributes: attributes)

// Example for a UILabel
let lbl = UILabel()
lbl.attributedText = attributedStr

文档NSAttributedStringhttps ://developer.apple.com/documentation/foundation/nsattributedstring


推荐阅读