属性化字符串,用到的时候问题一大堆,一一记下。
UITextView , UILabel , 都可以使用属性化字符串.
以UILabel为例,如下代码.
//函数作用:添加统计数据label; 参数text是数据(包括单位),如:3600分; 参数unit是单位,如: 分
- (void)addLabelBy:(CGRect)frame withText:(NSString *)text inView:(UIView *)view unit:(NSString *)unit size:(CGFloat)high{
//属性化字符串
NSMutableAttributedString *atrString=[[NSMutableAttributedString alloc]initWithString:text];
NSUInteger length=[atrString length];
//不同字体
UIFont *dataFont=[UIFont fontWithName:@"Georgia-Bold" size:high];
UIFont *unitFont=[UIFont systemFontOfSize:high/2];
//把数据和单位设置成 不同字体和颜色
[atrString addAttribute:NSFontAttributeName value:dataFont range:NSMakeRange(0, length)];
[atrString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, length)];
[atrString addAttribute:NSFontAttributeName value:unitFont range:[text rangeOfString:unit]];
[atrString addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:[text rangeOfString:unit]];
//添加label
UILabel *label=[[UILabel alloc]initWithFrame:frame];
label.attributedText=atrString;
label.textAlignment=NSTextAlignmentCenter;
[view addSubview:label];
}
3.在UITextView 中涉及到换行,要加\n,对属性化字符串一样有效
4.顺便说下,UITextView顶部空白,需要设置self.automaticallyAdjustsScrollViewInsets = NO;
5.属性化字符串 属性列举
NSString *const NSFontAttributeName;(字体)
NSString *const NSParagraphStyleAttributeName;(段落)
NSString *const NSForegroundColorAttributeName;(字体颜色)
NSString *const NSBackgroundColorAttributeName;(字体背景色)
NSString *const NSLigatureAttributeName;(连字符)
NSString *const NSKernAttributeName;(字间距)
NSString *const NSStrikethroughStyleAttributeName;(删除线)
NSString *const NSUnderlineStyleAttributeName;(下划线)
NSString *const NSStrokeColorAttributeName;(边线颜色)
NSString *const NSStrokeWidthAttributeName;(边线宽度)
NSString *const NSShadowAttributeName;(阴影)(横竖排版)
NSString *const NSVerticalGlyphFormAttributeName;
原文:http://my.oschina.net/u/2262643/blog/529127