iOS 在UILabel显示不同的字体和颜色
2015-09-01 22:32
260 查看
在项目开发中,我们经常会遇到在这样一种情形:在一个UILabel 使用不同的颜色或不同的字体来体现字符串,在iOS 6 以后我们可以很轻松的实现这一点,官方的API 为我们提供了UILabel类的attributedText, 使用不同颜色和不同字体的字符串,我们可以使用NSAttributedText 和
NSMutableAttributedText 类来实现。
现实代码:
.h 文件
.m文件 在viewDidLoad方法中添加以下代码:
效果图:
如果想在iOS6.0以前版本实现这个效果,需要使用到一个第三方库TTTAttributedLabel,同时还有导入CoreText.frame框架.
NSMutableAttributedText 类来实现。
现实代码:
.h 文件
@interface ViewController : UIViewController @property (nonatomic, strong) IBOutlet UILabel *attrLabel; - (IBAction)next:(id)sender; @end
.m文件 在viewDidLoad方法中添加以下代码:
self.title = @"For iOS 6 & later"; NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)]; [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)]; [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)]; [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)]; attrLabel.attributedText = str;
效果图:
如果想在iOS6.0以前版本实现这个效果,需要使用到一个第三方库TTTAttributedLabel,同时还有导入CoreText.frame框架.
相关文章推荐
- 图片拉伸通常我们开发中将其写到UIImage的分类中使用,下面可以直接复制使用
- UIday0703:用 UIScrollView 和 UIPageControl 实现轮播图
- UI多线程编程小练习--卖票系统
- UIday0702:用 UIScrollView 和 UIPageControl 实现引导图
- hdu 2818 Building Block (带权并查集,很优美的题目)
- 将UIView加载成WevView(不懂的可以留言)
- UI中常用的4种传值
- Win10开发:视觉状态VisualState与自适应UI
- UITabBar 自定义
- AbstractQueuedSynchronizer实现原理
- UVALive 4287 Proving Equivalence (强连通分量)
- Android UI设计(引导界面):ViewPager之基本用法
- java基础-GUI
- [DP!]UESTC 890
- LeetCode之Repeated DNA Sequences
- UI_UIGestureRecognizer(触摸手势)
- UINavigationController视图控制器
- iPhone第三节:UITableView(2)
- HDU 4893(Wow! Such Sequence!-线段树单点修改+区间求和+改为最近Fib数)
- InputFormat到key-value生成流程