要设置多种属性的话就要设置NSMutableAttributedString这个方法,他对于string类设置不同的熟悉,包括颜色,字体等多种属性。
先上代码:
NSMutableAttributedString *lab = [[NSMutableAttributedString alloc]initWithString:@"今天天气很好,秋高气爽,万里无云!啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"];
[lab addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(7, 4)];
[lab addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor blueColor].CGColor range:NSMakeRange(20, 4)];
CATextLayer *textlay = [CATextLayer layer];
textlay.string = lab;
textlay.frame = CGRectMake(100, 300, 200, 1000);
[self.view.layer addSublayer:textlay];
先将文字放入NSMutableAttributedString中,然后设置特殊属性的位置,最后通过CATextLayer将其在屏幕上显示。由于UILabel不支持NSMutableAttributedString,应此只能用CATextLayer。
运行代码会发现字体灰常的模糊,这时就要设置CATextLayer的contentsScale 熟悉,就能变清晰了。
textlay.contentsScale = 2;//防止模糊!!重要
当需要显示的内容过长,就需要自动换行,设置wrapped属性就行了。
[textlay setWrapped:YES];