iOS富文本

在iOS上能進(jìn)行文本顯示的控件有UILable,UITextField,UITextView。然而這些控件本身對(duì)文本的展現(xiàn)方式很單一,通常僅僅能夠控制字體樣式、大小、顏色、加粗、斜體等等,而對(duì)于行距控制,字距控制,段落控制等高級(jí)功能卻無(wú)能為力。

而iOS7的發(fā)布,蘋果又引入了TextKit,TextKit是一個(gè)快速而又現(xiàn)代化的文字排版和渲染引擎。

TextKit并沒(méi)有新增類,只是在原有的文本顯示控件上進(jìn)行了封裝,可以在平時(shí)我們最喜歡使用的UILabel,UITextField,UITextView等控件里面使用,其最主要的作用就是為程序提供文字排版和渲染的功能

1、NSMutableAttributedString的基本使用

富文本注意:
先設(shè)置的先顯示,后設(shè)置的,如果和先設(shè)置的樣式不一致,是會(huì)覆蓋的,富文本的設(shè)置具有先后順序。
不要忽略了空格也是一個(gè)字符。
建議使用靈活的好用的NSMutableAttributedString,不要使用NSAttributedString。
富文本基本使用方法的思路概要

1、創(chuàng)建一個(gè)NSMutableAttributedString富文本對(duì)象(一般不用NSAttributedString)
2、設(shè)置addAttribute屬性
(1) addAttribute: 一個(gè)屬性
(2) addAttributes: 一個(gè)存儲(chǔ)多個(gè)屬性的屬性字典,比如這個(gè)字典可以是:
NSDictionary *attrDic = @{
NSFontAttributeName: [UIFont fontWithName: @"Zapfino" size: 15],
NSForegroundColorAttributeName: [UIColor blueColor]
};
3、控件.attributedText = 富文本對(duì)象(和控件.txt = NSString文本對(duì)象不一樣的)


    NSString * str = @"some text bula bula";
    
    //添加富文本對(duì)象
    NSMutableAttributedString * attr = [[NSMutableAttributedString alloc]initWithString:str];
    //設(shè)置字體顏色為紅色
    [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 5)];
    //設(shè)置字體大小
    [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28] range:NSMakeRange(4, 5)];
    
    self.label.attributedText = attr;
Paste_Image.png

NSMutableAttributedString可以設(shè)置的屬性有:

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

2.NSTextAttachment圖文混排簡(jiǎn)單應(yīng)用


    //設(shè)置圖片
    NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
    //設(shè)置圖片屬性
    attachment.image = [UIImage imageNamed:@"selected"];
    //設(shè)置圖片的bounds
    attachment.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 180);
    //將attachment轉(zhuǎn)換成字符串屬性
    NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
    //把圖片插入到文本中
    [self.textView.textStorage insertAttributedString:attachmentString atIndex:0];

//也可以拼接到文本后面
//    [self.textView.textStorage appendAttributedString:attachmentString];
Paste_Image.png

textview的實(shí)際使用

  • 實(shí)現(xiàn)的過(guò)程如下:
    storage --> layoutManager --> textContainer --> textView

    // 裝載內(nèi)容的容器
    NSTextStorage *storage = [NSTextStorage new];
    [storage replaceCharactersInRange:NSMakeRange(0, 0)
                           withString:
     @"未選擇的路-弗羅斯特\n\n黃色的樹(shù)林里分出兩條路,\n可惜我不能同時(shí)去涉足,\n我在那路口久久佇立,\n我向著一條路極目望去,\n直到它消失在叢林深處。\n但我卻選了另外一條路,\n它荒草萋萋,十分幽寂,\n顯得更誘人、更美麗,\n雖然在這兩條小路上,\n都很少留下旅人的足跡,\n雖然那天清晨落葉滿地,\n兩條路都未經(jīng)腳印污染。\n啊,留下一條路等改日再見(jiàn)!\n但我知道路徑延綿無(wú)盡頭,\n恐怕我難以再回返。\n也許多少年后在某個(gè)地方,\n我將輕聲嘆息把往事回顧,\n一片樹(shù)林里分出兩條路,\n而我選了人跡更少的一條,\n從此決定了我一生的道路。"];
    
    // 給內(nèi)容容器添加布局(可以添加多個(gè))
    NSLayoutManager *layoutManager = [NSLayoutManager new];
    [storage addLayoutManager:layoutManager];
    
    // 帶有內(nèi)容和布局的容器
    NSTextContainer *textContainer = [NSTextContainer new];
    [layoutManager addTextContainer:textContainer];
    
    // 給TextView添加帶有內(nèi)容和布局的容器
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 20, 300, 400)
                                               textContainer:textContainer];
    textView.layer.borderWidth = 1;
    textView.scrollEnabled = NO;
    textView.editable      = NO;
    [self.view addSubview:textView];

制作富文本,你可能會(huì)有一些定制的需求,比如圖片的高度不想每個(gè)都要設(shè)置一邊,你可以寫一個(gè)繼承,然后將下面方法重寫


-(CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex
{
  return CGRectMake( 0 , 0 , lineFrag.size.height , lineFrag.size.height);
}

替換文本內(nèi)容里面的字符為圖片


    //添加富文本對(duì)象
    NSMutableAttributedString * attachmentString = [[NSMutableAttributedString alloc]initWithString:str];
    //設(shè)置圖片
    NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
    //設(shè)置圖片屬性
    attachment.image = [UIImage imageNamed:@"selected"];
    //設(shè)置圖片的bounds
    attachment.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 180);
    
    NSAttributedString * text = [NSAttributedString attributedStringWithAttachment:attachment];
    
    NSRange range = [[attachmentString string] rangeOfString:@"icon"];
    
    [attachmentString replaceCharactersInRange:range withAttributedString:text];
    
    self.label.attributedText = attachmentString;

1.為某一范圍內(nèi)文字設(shè)置多個(gè)屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
為某一范圍內(nèi)文字添加某個(gè)屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

為某一范圍內(nèi)文字添加多個(gè)屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某范圍內(nèi)的某個(gè)屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
label.lineBreakMode = NSLineBreakByCharWrapping;以字符為顯示單位顯示,后面部分省略不顯示。
label.lineBreakMode = NSLineBreakByClipping;剪切與文本寬度相同的內(nèi)容長(zhǎng)度,后半部分被刪除。
label.lineBreakMode = NSLineBreakByTruncatingHead;前面部分文字以……方式省略,顯示尾部文字內(nèi)容。
label.lineBreakMode = NSLineBreakByTruncatingMiddle;中間的內(nèi)容以……方式省略,顯示頭尾的文字內(nèi)容。
label.lineBreakMode = NSLineBreakByTruncatingTail;結(jié)尾部分的內(nèi)容以……方式省略,顯示頭的文字內(nèi)容。
label.lineBreakMode = NSLineBreakByWordWrapping;以單詞為顯示單位顯示,后面部分省略不顯示。

UITextField 的富文本設(shè)置

NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:@"Hello world"];
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 5)];
    //設(shè)置字體大小
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(4, 5)];
    
    self.textField.attributedText = attri;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容