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];


屬性字符串基本上就那么多內容,只不過需要在應用中靈活運用而已。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容