不同颜色的 UILabel
UILabel With Different Colours
我在显示一些信息的自定义单元格中有一个标签。每个单元格中的信息都会不同,我想更改标签内一些 'keywords' 的颜色,以便它们脱颖而出。
我试过将文本转换为 NSMutableAttributedString
并在特定索引处更改文本颜色的方法。但是,关键字在文本中的位置在每个句子中都是不同的。有什么方法可以在关键字周围添加一些东西以便于识别它们吗?
编辑:这回答了我的问题:
Changing specific text's color using NSMutableAttributedString in Swift
您可以使用 attirbutedSring。不要忘记更改字体。
let string1 = "Your string";
let string2 = "your string 2";
let attributedString = NSMutableAttributedString(string: "“\(string1)” \(string2)", attributes: [
.font: UIFont(name: "IBMPlexSans", size: 15.0)!,
.foregroundColor: UIColor(red: 128.0 / 255.0, green: 130.0 / 255.0, blue: 135.0 / 255.0, alpha: 1.0),
.kern: 0.4
])
attributedString.addAttribute(.foregroundColor, value: UIColor(red: 1.0 / 255.0, green: 6.0 / 255.0, blue: 16.0 / 255.0, alpha: 1.0), range: NSRange(location: 0, length: string1.count));
yourLabel.attributedText = attributedString;
我在显示一些信息的自定义单元格中有一个标签。每个单元格中的信息都会不同,我想更改标签内一些 'keywords' 的颜色,以便它们脱颖而出。
我试过将文本转换为 NSMutableAttributedString
并在特定索引处更改文本颜色的方法。但是,关键字在文本中的位置在每个句子中都是不同的。有什么方法可以在关键字周围添加一些东西以便于识别它们吗?
编辑:这回答了我的问题:
Changing specific text's color using NSMutableAttributedString in Swift
您可以使用 attirbutedSring。不要忘记更改字体。
let string1 = "Your string";
let string2 = "your string 2";
let attributedString = NSMutableAttributedString(string: "“\(string1)” \(string2)", attributes: [
.font: UIFont(name: "IBMPlexSans", size: 15.0)!,
.foregroundColor: UIColor(red: 128.0 / 255.0, green: 130.0 / 255.0, blue: 135.0 / 255.0, alpha: 1.0),
.kern: 0.4
])
attributedString.addAttribute(.foregroundColor, value: UIColor(red: 1.0 / 255.0, green: 6.0 / 255.0, blue: 16.0 / 255.0, alpha: 1.0), range: NSRange(location: 0, length: string1.count));
yourLabel.attributedText = attributedString;