iOS NSAttributedString ,NSMutableAttributedString,NSMutableParagraphStyle的使用,UILabel设置行间距和字间距并计算高度

//给UILabel设置行间距和字间距
-(void)setLabelSpace:(UILabel*)label withValue:(NSString*)str withFont:(UIFont*)font {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    //设置字间距 NSKernAttributeName:@1.5f
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
};
    
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
    label.attributedText = attributeStr;
}

//计算UILabel的高度(带有行间距的情况)
-(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = UILABEL_LINE_SPACE;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
};
    
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

1、NSAttributedString 不可变属性字符串,创建出来之后不能修改其属性(属性都是只读的),但是可以在创建的时候直接附加属性设置(属性是针对所有文本),其属性介绍以及用法,直接在代码上标注如下:

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.frame), 300)];    label.numberOfLines = 0;  
 [self.view addSubview:label];   
 label.backgroundColor = [UIColor lightGrayColor];       
 NSString *string = @"今日头条是一款基于数据挖掘的推荐引擎产品,它为用户推荐有价值的、个性化的信息,提供连接人与信息的新型服务,是国内移动互联网领域成长最快的产品服务之一。";   
     NSMutableDictionary *dict = [NSMutableDictionary dictionary];   
 dict[NSForegroundColorAttributeName] = [UIColor redColor]; // UIColor,文本前景颜色,默认是blackColor    dict[NSBackgroundColorAttributeName] = [UIColor yellowColor];// UIColor,文本背景颜色(不是控件View的背景颜色),默认nil    dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];// UIFont,文本字体大小,默认 Helvetica(Neue) 12  
    /*  文本段落样式(详细段落样式见下方)     //    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];     //    paragraphStyle.lineSpacing = 10;                  // 段落行距     */   
     dict[NSParagraphStyleAttributeName] = paragraphStyle;    // NSParagraphStyle,文本段落样式    
/*//删除线和下划线
枚举常量 NSUnderlineStyle中的值    NSUnderlineStyleNone        //不设置删除线    NSUnderlineStyleSingle      // 设置删除线为细单实线    NSUnderlineStyleThick       //   设置删除线为粗单实线    NSUnderlineStyleDouble    // 设置删除线为细双实线     NSUnderlinePatternSolid        NSUnderlinePatternDot     //点    NSUnderlinePatternDash  //虚线    NSUnderlinePatternDashDot  //虚线和点    NSUnderlinePatternDashDotDot  //虚线和点点    NSUnderlineByWord 
*/    dict[NSStrikethroughStyleAttributeName] = @(NSUnderlinePatternSolid | NSUnderlineStyleSingle);      // NSNumber,加删除线,默认不加删除线,其它的话是加不同风格的删除线    dict[NSStrikethroughColorAttributeName] = [UIColor yellowColor];          // UIColor,删除线颜色,默认等于文本前景颜色,前提是需要加删除线,和NSStrikethroughStyleAttributeName有关    dict[NSUnderlineStyleAttributeName] = @(NSUnderlineStyleDouble);          // NSNumber,加下划线,默认NSUnderlineStyleNone不加下划线,其它的话是加不同的下划线    dict[NSUnderlineColorAttributeName] = [UIColor yellowColor];              // UIColor,下划线颜色,默认等于文本前景颜色,前提是需要加下划线,和NSUnderlineStyleAttributeName有关
    dict[NSStrokeColorAttributeName] = [UIColor yellowColor];                 // UIColor,默认等于文本前景颜色,需要和NSStrokeWidthAttributeName一起使用    dict[NSStrokeWidthAttributeName] = @5;                                    // NSNumber,使文本有一种中空的效果(有立体效果)数字越大,文本填充的越满,数字越小,文本颜色越淡,不需要和NSStrokeColorAttributeName一起使用        /* 文本阴影     NSShadow *shadow = [[NSShadow alloc] init];     shadow.shadowOffset = CGSizeMake(2, 3);      阴影偏移量     shadow.shadowColor = [UIColor yellowColor];  阴影颜色     shadow.shadowBlurRadius = 1.0;               阴影圆角     */    dict[NSShadowAttributeName] = shadow;  // NSShadow,默认没有阴影,    
    dict[NSKernAttributeName] = @10; // NSNumber,文本字间距(字与字之间的距离)    dict[NSLinkAttributeName] = [NSURL URLWithString:@"http:baidu.com"];      // NSURL或者是链接字符串,文本链接样式,自带下划线,文本颜色是蓝色    dict[NSLinkAttributeName] = @"http:baidu.com"; // NSURL或者是链接字符串,文本链接样式,自带下划线,文本颜色是蓝色    dict[NSExpansionAttributeName] = @(-0.5);  // NSNumber,本文的扩张倍数,负数的话相当于缩小    dict[NSObliquenessAttributeName] = @(0.7); // NSNumber,本文的斜体程度以及斜体方向,默认0不歪斜,负数相当于右斜,正数相当于左斜,歪斜的程度由数字的大小决定    dict[NSBaselineOffsetAttributeName] = @(15.0);  // NSNumber,行文本基线的偏移量        dict[NSWritingDirectionAttributeName] = @[@(NSWritingDirectionOverride),@(NSWritingDirectionRightToLeft)]; // 貌似是文本写入方向    dict[NSVerticalGlyphFormAttributeName] = @(1); // 文本的垂直与水平,目前在[iOS](http://lib.csdn.net/base/ios),它总是水平,任何其他值的行为是未定义的        NSTextAttachment *textAtt = [[NSTextAttachment alloc] init];    textAtt.image = [UIImage imageNamed:@"cloud.png"];    dict[NSAttachmentAttributeName] = textAtt; // 在文本中插入表情        label.attributedText = [[NSAttributedString alloc] initWithString:string attributes:dict];

2、NSMutableAttributedString可变属性字符串,创建出来之后可修改其属性,也可以给文本在某一个范围内添加单个属性或者字典属性(一次性添加很多属性),比如一个属性字符串不同范围的颜色不一样,其属性介绍以及用法,直接在代码上标注如下:

     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.frame), 300)];    label.numberOfLines = 0;    [self.view addSubview:label];    label.backgroundColor = [UIColor lightGrayColor];        NSString *string = @"今日头条是一款基于数据挖掘的推荐引擎产品,它为用户推荐有价值的、个性化的信息,提供连接人与信息的新型服务,是国内移动互联网领域成长最快的产品服务之一。";        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:string];    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];    [paragraphStyle setLineSpacing:10];        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];    //    [attributedString addAttributes:<#(nonnull NSDictionary<NSString *,id> *)#> range:<#(NSRange)#>]; // 添加字典属性    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 10)];        label.attributedText = attributedString;

NSMutableParagraphStyle的部分属性:

typedef NS_ENUM(NSInteger, NSLineBreakMode) {/* What to do with long lines */  
    NSLineBreakByWordWrapping = 0,     /* Wrap at word boundaries, default */  
    NSLineBreakByCharWrapping,/* Wrap at character boundaries */  
    NSLineBreakByClipping,/* Simply clip */剪掉后面显示不了的部分  
    NSLineBreakByTruncatingHead,/* Truncate at head of line: "...wxyz" */头部分的内容以……方式省略  
    NSLineBreakByTruncatingTail,/* Truncate at tail of line: "abcd..." */结尾部分的内容以……方式省略  
    NSLineBreakByTruncatingMiddle/* Truncate middle of line:  "ab...yz" */中间部分的内容以……方式省略  
} NS_ENUM_AVAILABLE_IOS(6_0);  
  
  
  
  
  
typedef NS_ENUM(NSInteger, NSWritingDirection) {  
    NSWritingDirectionNatural       = -1,    // Determines direction using the Unicode Bidi Algorithm rules P2 and P3  
    NSWritingDirectionLeftToRight   =  0,    // Left to right writing direction 左到右的书写方向  
    NSWritingDirectionRightToLeft   =  1    // Right to left writing direction 右到左的书写方向  
} NS_ENUM_AVAILABLE_IOS(6_0);  
  
  
  
  
  
  
  
 //   NSParagraphStyleAttributeName 段落的风格(设置首行,行间距,对齐方式什么的)看自己需要什么属性,写什么  
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];  
    paragraphStyle.lineSpacing = 10;// 字体的行间距  
    paragraphStyle.firstLineHeadIndent = 20.0f;//首行缩进  
    paragraphStyle.alignment = NSTextAlignmentJustified;//(两端对齐的)文本对齐方式:(左,中,右,两端对齐,自然)  
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")  
    paragraphStyle.headIndent = 20;//整体缩进(首行除外)  
    paragraphStyle.tailIndent = 20;//  
    paragraphStyle.minimumLineHeight = 10;//最低行高  
    paragraphStyle.maximumLineHeight = 20;//最大行高  
    paragraphStyle.paragraphSpacing = 15;//段与段之间的间距  
    paragraphStyle.paragraphSpacingBefore = 22.0f;//段首行空白空间/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */  
    paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;//从左到右的书写方向(一共??三种)  
    paragraphStyle.lineHeightMultiple = 15;/* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */  
    paragraphStyle.hyphenationFactor = 1;//连字属性 在iOS,唯一支持的值分别为0和1  
  
  
  
  
  
  
  
/* 
     NSFontAttributeName 字体大小 
     NSParagraphStyleAttributeName 段落的风格(设置首行,行间距,对齐方式什么的) 
     NSKernAttributeName 字间距 
     */  
    NSDictionary *attributes = @{  
                                 NSFontAttributeName:[UIFont systemFontOfSize:15],  
                                 NSParagraphStyleAttributeName:paragraphStyle,  
                                 NSKernAttributeName:@(10),  
                                                                
                                 };  
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];

3、NSMutableParagraphStyle
用于设定文本段落有关设置,比如行间距,文本缩进,段间距等等,其用法如下:

 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.frame), 300)];
    label.numberOfLines = 0;
    [self.view addSubview:label];
    label.backgroundColor = [UIColor lightGrayColor];
    
    NSString *string = @"今日头条是一款基于数据挖掘的推荐引擎产品,它为用户推荐有价值的、个性化的信息,提供连接人与信息的新型服务,是国内移动互联网领域成长最快的产品服务之一。";
    /*  文本段落样式
     //    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
     //    paragraphStyle.lineSpacing = 10;                  // 段落行距
     //    paragraphStyle.headIndent = 5;                    // 非首行文本缩进
     //    paragraphStyle.tailIndent = -20;                  // 文本缩进(右端)
     //    paragraphStyle.firstLineHeadIndent = 20;          // 首行文本缩进
     //    paragraphStyle.alignment = NSTextAlignmentRight;  // 文本对齐方式
     //    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; // 折行方式
     //    paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight; // 文本写入方式
     //    paragraphStyle.lineHeightMultiple = 3.0;          // 文本行间距是默认行间距的多少倍
     //    paragraphStyle.maximumLineHeight = 50;            // 文本最大行距
     //    paragraphStyle.minimumLineHeight = 50;            // 文本最小行距
     //    paragraphStyle.allowsDefaultTighteningForTruncation = YES; // 目前还不知道有什么作用
     
     //    paragraphStyle.hyphenationFactor = 1.0; // 设置每行的最后单词是否截断,在0.0-1.0之间,默认为0.0,越接近1.0单词被截断的可能性越大,
     
     //    paragraphStyle.paragraphSpacing = 10;             // 段落后面的间距
     //    paragraphStyle.paragraphSpacingBefore = 20;       //设置段与段之间的距离
     */
    //    dict[NSParagraphStyleAttributeName] = paragraphStyle;                     // NSParagraphStyle,文本段落样式
    label.attributedText = [[NSAttributedString alloc] initWithString:string attributes:dict];


属性字符串基本上就那么多内容,只不过需要在应用中灵活运用而已。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容