1、NSMutableAttributeString能实现图文混排,UILabel 和 UITextView 都能添加 NSAttributedString 属性字符串,通过这一点,可以实现带有属性的文字和文字内包含图片的文本内容展示.
//NSMutableAttributeString的相关创建
- (void)viewDidLoad {
NSString*string = @"如何使得Label里的字符有不同的颜色?";
NSRange range = [string rangeOfString: @"Label"];
NSMutableAttributedString* attribute = [[NSMutableAttributedString alloc] initWithString: string];
[attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor redColor]}range: range];
[attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor greenColor]}range: NSMakeRange(0, range.location)];
[attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor cyanColor]}range: NSMakeRange(range.location+ range.length, 5)];
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0.0f, 100.0f, 320.0f, 100.0f)];
[label setAttributedText: attribute];
[self.view addSubview:label];
}