请问能否自定义 UIButton 的 titleLabel 呢,需求是想自定义 UILabel 中 text 显示不同颜色

2015-04-11 12:54:02 +08:00
 lcl22hope
google 后找到的各种资料都是 NSAttributeString 给 label 的 string 增加属性,然后在重新写 UILabel 的 drawRect 方法,请问有没有其他方式呢,多谢!
2834 次点击
所在节点    iDev
5 条回复
blankwonder
2015-04-11 12:56:38 +08:00
- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state
lcl22hope
2015-04-11 12:58:56 +08:00
@blankwonder 谢谢回答,这个方法我试过,它可以更改全部文字的颜色,但想只改变一部分,比如:备注1:hello world,“备注1:”部分想用绿色展示,但hello world用黑色
qq2511296
2015-04-11 13:27:46 +08:00
_label.text = @"备注1:hello world";
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:_label.text];
[attr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:[_label.text rangeOfString:@"备注1:"]];
[attr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:[_label.text rangeOfString:@"hello world"]];
_label.attributedText = attr;
lcl22hope
2015-04-11 14:39:15 +08:00
@qq2511296 非常感谢,测试有效
lzyroot
2015-04-13 10:12:12 +08:00
@qq2511296 mark

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/183033

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX