富文本和段落間距,讓你的文字更有魅力

在iOS開發(fā)中,常常會有一段文字顯示不同的顏色和字體,或者給某幾個文字加刪除線或下劃線的需求。之前在網(wǎng)上找了一些資料,有的是重繪UILabel的textLayer,有的是用HTML5實現(xiàn)的,都比較麻煩,而且很多UILabel的屬性也不起作用了,效果都不理想。但是NSMuttableAttstring(帶屬性的字符串)和NSMutableParagraphStyle,上面的一些需求都可以很簡便的實現(xiàn)。

NSMuttableAttstring 富文本

先看代碼

    UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)];
    testLabel.backgroundColor = [UIColor lightGrayColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"今天天氣不錯呀"];
    [AttributedStr addAttribute:NSFontAttributeName
                          value:[UIFont systemFontOfSize:25.0]
                          range:NSMakeRange(2, 2)];
    [AttributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor redColor]
                          range:NSMakeRange(2, 2)];
    testLabel.attributedText = AttributedStr;
    [self.view addSubview:testLabel];
今天天氣不錯呀
 UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)];
    testLabel.backgroundColor = [UIColor lightGrayColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    
    NSDictionary*attributes =@{NSForegroundColorAttributeName: [UIColor redColor
                                                                ],
                               NSFontAttributeName: [UIFont fontWithName:@"Zapfino"size:13.0]
                               };
    NSString*strDisplayText =@"This is an attributed string.";
    NSAttributedString*attributedText = [[NSAttributedString alloc]initWithString:strDisplayText attributes:attributes];
    testLabel.attributedText= attributedText;
    [self.view addSubview:testLabel];
今天天氣不錯呀
  UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)];
    testLabel.backgroundColor = [UIColor lightGrayColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    NSString *cstrTitle = @"This is an attributed string.下劃線";
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:cstrTitle attributes:attribtDic];
    testLabel.attributedText = attribtStr;
    [self.view addSubview:testLabel];
下劃線
  UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 300)];
    testLabel.numberOfLines = 0;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"很好玩的富文本"];
    [string addAttribute:NSUnderlineStyleAttributeName value:@(2) range:NSMakeRange(4, 3)];
    [string addAttribute:NSUnderlineColorAttributeName value:[UIColor blueColor] range:NSMakeRange(4, 3)];
    testLabel.attributedText = string;
    [self.view addSubview:testLabel];
下劃線

看著效果還不錯,下面看看具體用法

使用方法:
為某一范圍內(nèi)文字設置多個屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
為某一范圍內(nèi)文字添加某個屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
為某一范圍內(nèi)文字添加多個屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某范圍內(nèi)的某個屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
常見的屬性及說明
// NSFontAttributeName                設置字體屬性,默認值:字體:Helvetica(Neue) 字號:12
// NSForegroundColorAttributeNam      設置字體顏色,取值為 UIColor對象,默認值為黑色
// NSBackgroundColorAttributeName     設置字體所在區(qū)域背景顏色,取值為 UIColor對象,默認值為nil, 透明色
// NSLigatureAttributeName            設置連體屬性,取值為NSNumber 對象(整數(shù)),0 表示沒有連體字符,1 表示使用默認的連體字符
// NSKernAttributeName                設定字符間距,取值為 NSNumber 對象(整數(shù)),正值間距加寬,負值間距變窄
// NSStrikethroughStyleAttributeName  設置刪除線,取值為 NSNumber 對象(整數(shù))
// NSStrikethroughColorAttributeName  設置刪除線顏色,取值為 UIColor 對象,默認值為黑色
// NSUnderlineStyleAttributeName      設置下劃線,取值為 NSNumber 對象(整數(shù)),枚舉常量 NSUnderlineStyle中的值,與刪除線類似
// NSUnderlineColorAttributeName      設置下劃線顏色,取值為 UIColor 對象,默認值為黑色
// NSStrokeWidthAttributeName         設置筆畫寬度,取值為 NSNumber 對象(整數(shù)),負值填充效果,正值中空效果
// NSStrokeColorAttributeName         填充部分顏色,不是字體顏色,取值為 UIColor 對象
// NSShadowAttributeName              設置陰影屬性,取值為 NSShadow 對象
// NSTextEffectAttributeName          設置文本特殊效果,取值為 NSString 對象,目前只有圖版印刷效果可用:
// NSBaselineOffsetAttributeName      設置基線偏移值,取值為 NSNumber (float),正值上偏,負值下偏
// NSObliquenessAttributeName         設置字形傾斜度,取值為 NSNumber (float),正值右傾,負值左傾
// NSExpansionAttributeName           設置文本橫向拉伸屬性,取值為 NSNumber (float),正值橫向拉伸文本,負值橫向壓縮文本
// NSWritingDirectionAttributeName    設置文字書寫方向,從左向右書寫或者從右向左書寫
// NSVerticalGlyphFormAttributeName   設置文字排版方向,取值為 NSNumber 對象(整數(shù)),0 表示橫排文本,1 表示豎排文本
// NSLinkAttributeName                設置鏈接屬性,點擊后調(diào)用瀏覽器打開指定URL地址
// NSAttachmentAttributeName          設置文本附件,取值為NSTextAttachment對象,常用于文字圖片混排
// NSParagraphStyleAttributeName      設置文本段落排版格式,取值為 NSParagraphStyle 對象

NSMutableParagraphStyle 段落間距

先看代碼

    UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 400)];
    testLabel.numberOfLines = 0;
    testLabel.backgroundColor = [UIColor lightGrayColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    NSString *cstrTitle = @"相愛的樂章里,分手的重音也會輕輕跳過,劃成歡快節(jié)拍。打算分手那天,弘帶著敏和她的兒子來到海邊。玩累了的孩子在一邊沉沉睡去偎坐打算分手那天,弘帶著敏和她的兒子來到海邊。玩累了的孩子在一邊沉沉睡去,他們靜靜地偎坐在一起,望向海天之際。\n弘情不自禁地對敏說:我們不回去了好不好?相愛的樂章里,分手的重音也會輕輕跳過,劃成歡快節(jié)拍。打算分手那天,弘帶著敏和她的兒子來到海邊。玩累了的孩子在一邊沉沉睡去,他們靜靜地偎坐在一起,望向海天之際。弘情不自禁地對敏說:我們不回去了好不好?";
    NSMutableAttributedString* muAttrString = [[NSMutableAttributedString alloc] initWithString:cstrTitle];
    NSMutableParagraphStyle *paragtaphStyle = [NSMutableParagraphStyle new];
    paragtaphStyle.alignment = NSTextAlignmentJustified;
    paragtaphStyle.paragraphSpacing = 14.0;
    paragtaphStyle.paragraphSpacingBefore = 10;
    paragtaphStyle.firstLineHeadIndent = 0.0;
    paragtaphStyle.headIndent = 0.0;
    paragtaphStyle.lineSpacing = 5;
    NSDictionary *dic = @{NSForegroundColorAttributeName: [UIColor redColor],
                          NSFontAttributeName           : [UIFont systemFontOfSize:15],
                          NSParagraphStyleAttributeName :  paragtaphStyle,
                          NSUnderlineStyleAttributeName :  [NSNumber numberWithInteger:NSUnderlineStyleNone]};
    [muAttrString setAttributes:dic range:NSMakeRange(0, muAttrString.length)];
    
    NSAttributedString *attrString = [muAttrString copy];
    testLabel.attributedText = attrString;
    [self.view addSubview:testLabel];
段落間距
常見的屬性及說明
// alignment               對齊方式,取值枚舉常量 NSTextAlignment
// firstLineHeadIndent     首行縮進,取值 float
// headIndent              縮進,取值 float
// tailIndent              尾部縮進,取值 float
// ineHeightMultiple       可變行高,乘因數(shù),取值 float
// maximumLineHeight       最大行高,取值 float
// minimumLineHeight       最小行高,取值 float
// lineSpacing             行距,取值 float
// paragraphSpacing        段距,取值 float
// paragraphSpacingBefore  段首空間,取值 float
//    
// baseWritingDirection    句子方向,取值枚舉常量 NSWritingDirection
// lineBreakMode           斷行方式,取值枚舉常量 NSLineBreakMode
// hyphenationFactor       連字符屬性,取值 0 - 1
具體使用如下
 //   NSParagraphStyleAttributeName 段落的風格(設置首行,行間距,對齊方式什么的)看自己需要什么屬性,寫什么  
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];  
    paragraphStyle.lineSpacing = 10;// 字體的行間距  
    paragraphStyle.firstLineHeadIndent = 20.0f;//首行縮進  
    paragraphStyle.alignment = NSTextAlignmentJustified;//(兩端對齊的)文本對齊方式:(左,中,右,兩端對齊,自然)  
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//結尾部分的內(nèi)容以……方式省略 ( "...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]; 

開發(fā)過程中,經(jīng)常會遇到動態(tài)計算行高的問題, 但是遇到行高間距就會出現(xiàn)問題

下面是計算高度寬度的方法總結
/**
 *  計算字符串高度
 *
 *  @param string     字符串
 *  @param font       大小
 *  @param width      寬度
 *  @param pageWidth  行之間間距
 *
 *  @return 高度
 */
+ (CGFloat)getTheStringHeight:(NSString *)string setFont:(CGFloat)font withWidth:(CGFloat)width andParaWidth:(CGFloat)pageWidth
{
    if (string == nil || [string isEqualToString:@""])
    {
        return 0;
    }

    NSMutableAttributedString  *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = NSMakeRange(0, attrStr.length);
    //段落
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    [paragraphStyle setLineSpacing:pageWidth];
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    //設置字體
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:font]
                    range:range];
    
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];   // 獲取該段attributedString
    
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) // 用于計算文本繪制時占據(jù)的矩形塊</span>
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本繪制時的附加選項
                                        attributes:dic        // 文字的屬性
                                           context:nil].size; // context上下文。包括一些信息,例如如何調(diào)整字間距以及縮放。該對象包含的信息將用于文本繪制。該參數(shù)可為nil
    
    return textSize.height;
}

/**
 *  計算字符串寬度
 *
 *  @param string     字符串
 *  @param font       大小
 *  @param height     高度
 *
 *  @return 寬度
 */
+ (CGFloat)getTheStringWidth:(NSString *)string setFont:(CGFloat)font withHeight:(CGFloat)height
{
    
    NSMutableAttributedString  *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = NSMakeRange(0, attrStr.length);
    //設置字體
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:font]
                    range:range];
    
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];   // 獲取該段attributedString
    
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, height) // 用于計算文本繪制時占據(jù)的矩形塊
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本繪制時的附加選項
                                        attributes:dic        // 文字的屬性
                                           context:nil].size; // context上下文。包括一些信息,例如如何調(diào)整字間距以及縮放。該對象包含的信息將用于文本繪制。該參數(shù)可為nil
    
    return textSize.width;
    
}
參考資料:

http://www.itnose.net/detail/6177538.html
http://www.itdecent.cn/p/10b7c87462fd
http://www.itdecent.cn/p/76cf230cfa31

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容