ios - 如何以编程方式在涉及动态文本的同一标签中提供不同的字体颜色

标签 ios objective-c uilabel nsattributedstring

您好 下面是我需要使用 UILabel 实现的那种 View 。我听说过 NSAttributedString 但不确定如何使用它进行动态文本加载。

enter image description here

这里整个文本字体是Roboto-Light。但是,我必须从前两位医生的 API 响应中替换文本“Andrew Murphy,John Smith”,并从 API 中获取“23 位医生”的计数,以便相应地调整此标签。您所看到的文本颜色取决于文本是恒定的还是动态的。我不确定如何实现它。因此,一些代码片段非常受欢迎。

谢谢!

最佳答案

您可以像这样将 NSMutableAttributeString 与 addAttribute:value:range 一起使用;

//Your entry string
NSString *myString = @"I have to replace text 'Dr Andrew Murphy, John Smith' ";
//Create mutable string from original one
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString];

//Fing range of the string you want to change colour
//If you need to change colour in more that one place just repeat it
NSRange range = [myString rangeOfString:@"John Smith"];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:range];

//Add it to the label - notice its not text property but it's attributeText
label.attributedText = attString;

希望对你有帮助

关于ios - 如何以编程方式在涉及动态文本的同一标签中提供不同的字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21024340/

相关文章:

ios - 使用 Swift 创建 iOS 应用程序,需要知道如何使用 mysql 数据库跟踪用户数据?

objective-c - 如何使用 url 数组填充 UIImageView?

iphone - 使用 Chipmunk 物理引擎创建椭圆

ios - UILabel 自动调整大小并在必要时添加滚动条?

android - 将 React 或 React Native 嵌入到现有的移动应用程序中

ios - 回到前台时重新启动动画

ios - 用于潜望镜式评论的 Swift 动画

objective-c - NSDictionary 和 NSArray

ios - 找到UILabel的底部位置,以便可以在下面创建第二个UILabel

ios - 动态调整 UILabel 的大小