简体   繁体   English

如何在 swift %@ 中更改部分动态字符串的颜色?

[英]How to change color of part of dynamic string in swift %@?

I am using the following placeholder in my string: %@我在我的字符串中使用以下占位符: %@

For instance my string is String(format: "greetings %@", str)例如我的字符串是String(format: "greetings %@", str)

How can I provide a specific color for this dynamic placeholder?如何为这个动态占位符提供特定颜色?

You can modify the attributes for a NSRange within an attributed string.您可以在属性字符串中修改NSRange的属性。 But rather than build it with a format string and retroactively going back and updating the attributes for a NSRange , I'd just create an attributed string for the string to be appended, setting its attributes before you append it:但是,与其使用格式字符串构建它并追溯返回并更新NSRange的属性,我只是为要附加的字符串创建一个属性字符串,在附加之前设置其属性:

let name = NSAttributedString(string: str, attributes: [.foregroundColor: UIColor.green])

let greeting = NSMutableAttributedString(string: "greetings ")
greeting.append(name)

label.attributedText = greeting

That yields:这产生:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM