iOS 富文本使用

最近想實現一個功能,如圖:

每月價格

最初實現的時候想到了用兩個Label,來實現,第一個顯示¥4000,設置一個字體,第二個顯示/月,設置另一個字體.這樣就能實現這個效果了,但是最后想一想還是用富文本比較好,順便可以學習一下.

今天我們先實現這個簡單的效果.
先創建一個Label:

-(UILabel *)priceLabel{
    if (_priceLabel == nil) {
        _priceLabel = [[UILabel alloc]init];
        _priceLabel.font = kFONT(13);
        _priceLabel.textColor = kColorTheme;
        _priceLabel.textAlignment = NSTextAlignmentRight;
    }
    return _priceLabel;
}

自己再創建一個私有方法,把字符串(比如:¥4000/月)傳進來,進行轉換,返回富文本,賦值給所需要的Label.

-(NSMutableAttributedString *)getPriceAttribute:(NSString *)string{
    
    NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:string];
    //目的是想改變 ‘/’前面的字體的屬性,所以找到目標的range
    NSRange range = [string rangeOfString:@"/"];
    NSRange pointRange = NSMakeRange(0, range.location);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[NSFontAttributeName] = [UIFont systemFontOfSize:18];
    //賦值
    [attribut addAttributes:dic range:pointRange];    
    return attribut;
}

首先創建一個富文本NSMutableAttributedString對象,把傳進來的NSString對象轉化為NSMutableAttributedString對象.
然后對NSMutableAttributedString進行設置.
NSRange range = [string rangeOfString:@"/"];取到一個標志的位置:range,然后對"/"前面的文字進行設置.

然后,返回富文本,再進行賦值.

  _priceLabel.attributedText = [self getPriceAttribute:@"¥4000/月"]; 

上面只是一個簡單應用,還有很多常用到的富文本.比如,文字和圖片的混排,文字點擊事件.等等.

我們依次實現一些功能

在指定位置添加圖片

NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:@"不要問我為什么編程,我喜歡手指在鍵盤上飛舞的感覺"];
[attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
[attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];

添加圖片到指定的位置

NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
// 表情圖片
attchImage.image = [UIImage imageNamed:@"pic3"];
// 設置圖片大小
attchImage.bounds = CGRectMake(0, -5, 20, 20);
NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
[attriStr insertAttributedString:stringImage atIndex:2];

追加圖片到最后一位

NSTextAttachment *attch = [[NSTextAttachment alloc] init];
// 表情圖片
attch.image = [UIImage imageNamed:@"pic2"];
// 設置圖片大小
attch.bounds = CGRectMake(0, -5, 20, 15);
// 創建帶有圖片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attriStr appendAttributedString:string];

設置中間位置文字為紅色

[attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6, 4)];
[attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(6, 4)];

綜合寫法

NSDictionary * attriBute = @{NSForegroundColorAttributeName:[UIColor yellowColor],NSFontAttributeName:[UIFont systemFontOfSize:25]};
[attriStr addAttributes:attriBute range:NSMakeRange(10, 4)];

賦值

self.attrobiuteLabel.attributedText = attriStr;

效果圖:

效果圖

最后認識一下各個屬性的意思:

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

格式&排版

上面屬性的最后一個就是排版.需要去一NSMutableParagraphStyle的對象.直接上代碼:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = aligent;
paragraphStyle.lineSpacing = lineSpace; // 調整行間距
paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;//首行縮進
NSRange range = NSMakeRange(0, [string length]);
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];

我們再來認識一下NSMutableParagraphStyle的屬性:

CGFloat lineSpacing;                 // 字體的行間距 
CGFloat paragraphSpacing;            // 段與段之間的間距  
NSTextAlignment alignment;           // (兩端對齊的)文本對齊方式(左,中,右,兩端對齊,自然)   
CGFloat firstLineHeadIndent;         // 首行縮進    
CGFloat headIndent;                  // 整體縮進(首行除外)    
CGFloat tailIndent;                  // 尾部縮進
NSLineBreakMode lineBreakMode;       // 結尾部分的內容以……方式省略
CGFloat minimumLineHeight;           // 最低行高
CGFloat maximumLineHeight;           // 最大行高    
NSWritingDirection baseWritingDirection; // 書寫方向
CGFloat lineHeightMultiple;          // 行間距多少倍
CGFloat paragraphSpacingBefore;      // 段首行空白空
float hyphenationFactor;             // 連字屬性 在iOS,唯一支持的值分別為0和1  

設置了這么多的格式,進行了各種各樣的排版那么怎么計算行高呢.

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 6_0);

是蘋果推薦的計算方法,顯然會遇到段落格式問題,例如行間距、縮進等格式設置需求,attributes傳進來的字典中,包含我們設置的字體及格式,其中NSParagraphStyleAttributeName是設置段落風格,NSFontAttributeName是設置字體。

如何把文章排版變得更好看,點擊:Markdown使用指南(常用語法,干貨).

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

推薦閱讀更多精彩內容