iphone - 如何在 iOS 5.1 及更低版本的 UILabel 中创建多色文本

标签 iphone ios uilabel

我想创建一个包含不同颜色文本的标签。像这样,

enter image description here

我在 iOS 6 中使用 NSMutableAttributedString 完成了此操作

 NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: self.exerciseLbl.attributedText];
[text addAttribute: NSForegroundColorAttributeName value: [UIColor colorWithRed:(187/255.0) green:(57/255.0) blue:(38/255.0) alpha:1] range: NSMakeRange(0, 2)];
[self.exerciseLbl setAttributedText: text];

但这不适用于 iOS 5.1 及更低版本。那么我怎样才能在 iOS 5 中达到相同的结果。

最佳答案

/**(1)** Build the NSAttributedString *******/

NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
// for those calls we don't specify a range so it affects the whole string
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
// now we only change the color of "Hello"
 [attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
/**(2)** Affect the NSAttributedString to the OHAttributedLabel *******/
myAttributedLabel.attributedText = attrStr;`
// Use the "Justified" alignment
`myAttributedLabel.textAlignment = UITextAlignmentJustify;`

关于iphone - 如何在 iOS 5.1 及更低版本的 UILabel 中创建多色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17826547/

相关文章:

php - 某些设备未收到 Apple 推送通知

ios - 如何阻止 UILabel 将 "..."替换为省略号

ios - 为iOS中的特定部分文本设置斜体文本

iphone - iOS iTunes 文件共享问题

ios - 如何在 iOS 8 的 UINavigationViewController 中更改 UINavigationBar 的大小?

iphone - 有关如何将 revmob 本地通知集成到 iOS 应用程序所需的分步指南

iphone - 条码技术——智能手机应用程序

ios - 无法从我的应用程序中删除 testflight sdk

swift - 以编程方式固定宽度,动态高度 UILabel?

iphone - Core Animation (CABasicAnimation) 的不可预测行为