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

tec*_*vvy 4 objective-c nsattributedstring uilabel ios

嗨下面是我需要实现的视图UILabel.我听说过NSAttributedString但不确定如何使用它进行动态文本加载.

在此输入图像描述

整个文本字体是Roboto-Light.但是,我必须从前两位医生的API响应中替换文本'Andrew Murphy博士,John Smith',并从API获得"23位医生"的计数,以便相应地调整此标签.您可以看到的文本颜色取决于文本是常量还是动态.我不知道如何实现它.因此,一些代码片段真的很受欢迎.

谢谢!

Gre*_*reg 5

您可以将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;
Run Code Online (Sandbox Code Playgroud)

希望这有帮助