1. 程式人生 > >iOS富文字(NSAttributedString)---盡力弄全了

iOS富文字(NSAttributedString)---盡力弄全了

專案上要載入html格式的文字,學習一下富文字相關內容。

1.載入HTML標籤文字

因為解析的資料裡面有html標籤,就使用下面的程式碼把字串轉換成data,初始化時再用HTML型別,轉換為富文字。

 NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

引數options裡面的字典有三對key value

文件型別NSDocumentTypeDocumentAttribute
NSPlainTextDocumentType  // 普通文字
 NSRTFTextDocumentType   //  富文字
 NSRTFDTextDocumentType   // 帶附件的富文字
 NSHTMLTextDocumentType  // 這個可以載入HTML格式的文字

編碼格式NSCharacterEncodingDocumentAttribute
 [NSNumber numberWithInt:NSUTF8StringEncoding]; // 不再一一列舉
預設NSDefaultAttributesDocumentAttribute

這個不知道對應的value是什麼

2.富文字總結

這是富文字的所有屬性
屬性Name 幹啥的 型別
NSFontAttributeName 字號 UIFont 預設12
NSParagraphStyleAttributeName 段落樣式 NSParagraphStyle
NSForegroundColorAttributeName 前景色 UIColor
NSBackgroundColorAttributeName 背景色 UIColor
NSObliquenessAttributeName 字型傾斜 NSNumber
NSExpansionAttributeName 字型加粗 NSNumber 比例 0就是不變 1增加一倍
NSKernAttributeName 字間距 CGFloat
NSUnderlineStyleAttributeName 下劃線 1或0
NSUnderlineColorAttributeName 下劃線顏色 UIColor
NSStrikethroughStyleAttributeName 刪除線 1或0
NSStrikethroughColorAttributeName 刪除線顏色 UIColor
NSStrokeColorAttributeName same as ForegroundColor UIColor
NSStrokeWidthAttributeName 字型描邊 CGFloat
NSLigatureAttributeName 連筆字 沒看出效果 1或0
NSShadowAttributeName 陰影 NSShawdow
NSTextEffectAttributeName 設定文字特殊效果,目前只有圖版印刷效果可用 NSString
NSAttachmentAttributeName 設定文字附件,常用插入圖片 NSTextAttachment
NSLinkAttributeName 連結 NSURL (preferred) or NSString
NSBaselineOffsetAttributeName 基準線偏移 NSNumber
NSWritingDirectionAttributeName 文字方向 分別代表不同的文字出現方向等等,我想你一定用不到它 - - @[@(1),@(2)]
NSVerticalGlyphFormAttributeName 水平或者豎直文字 在iOS沒卵用,不支援豎版 1豎直 0水平

解釋一下其中的三個型別

段落樣式
段落樣式主要改行距、段距、首行縮排、最大最小行高、多倍行距等十幾個屬性,把這些總結了你就比我更全..


    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc]init];
    muParagraph.lineSpacing = 10; // 行距
    muParagraph.paragraphSpacing = 20; // 段距
    muParagraph.firstLineHeadIndent = 30; // 首行縮排
陰影

就三屬性,不用解釋了

 NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowOffset = CGSizeMake(2, 2);
    shadow.shadowColor = [UIColor orangeColor];
    shadow.shadowBlurRadius = 1;
附件
 NSTextAttachment *attachment=[[NSTextAttachment alloc] initWithData:nil ofType:nil];
    UIImage *img=[UIImage imageNamed:@"test.png"];
    attachment.image=img;
    attachment.bounds=CGRectMake(0, 0, 20, 20);
下面是我的富文字程式碼,可以copy過去直接試
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.attTV];

    //NSFontAttributeName   字號 UIFont 預設12
    //NSParagraphStyleAttributeName    段落樣式  NSParagraphStyle
    //NSForegroundColorAttributeName    前景色   UIColor
    //NSBackgroundColorAttributeName    背景色   UIColor
    //NSObliquenessAttributeName        字型傾斜     NSNumber
    //NSExpansionAttributeName          字型加粗     NSNumber  比例 0就是不變 1增加一倍
    //NSKernAttributeName               字間距   CGFloat
    //NSUnderlineStyleAttributeName     下劃線     1或0
    //NSUnderlineColorAttributeName     下劃線顏色
    //NSStrikethroughStyleAttributeName 刪除線   1或0
    //NSStrikethroughColorAttributeName 某種顏色
    //NSStrokeColorAttributeName        same as ForegroundColor
    //NSStrokeWidthAttributeName        CGFloat
    //NSLigatureAttributeName           連筆字  1或0  沒看出效果
    //NSShadowAttributeName             陰影    NSShawdow
    //NSTextEffectAttributeName          設定文字特殊效果,取值為 NSString 物件,目前只有圖版印刷效果可用:
    //NSAttachmentAttributeName         NSTextAttachment  設定文字附件,常用插入圖片
    //NSLinkAttributeName               連結  NSURL (preferred) or NSString
    //NSBaselineOffsetAttributeName     基準線偏移   NSNumber

    //NSWritingDirectionAttributeName   文字方向     @[@(1),@(2)]  分別代表不同的文字出現方向等等,我想你一定用不到它 - -
    //NSVerticalGlyphFormAttributeName  水平或者豎直文字  1豎直 0水平 在iOS沒卵用,不支援豎版

    NSParagraphStyle *paragraph = [[NSParagraphStyle alloc]init];
    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc]init];
    muParagraph.lineSpacing = 10; // 行距
    muParagraph.paragraphSpacing = 20; // 段距
    muParagraph.firstLineHeadIndent = 30; // 首行縮排


    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[@"asdasdflhjlfsaiollzislooa" dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];


    NSRange range = NSMakeRange(0, attrStr.length);
    // 設定字型大小
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:range];
    //字間距
    [attrStr addAttribute:NSKernAttributeName value:@(2) range:range];
    // 字型傾斜
    [attrStr addAttribute:NSObliquenessAttributeName value:@(1) range:range];
    // 字型加粗
    [attrStr addAttribute:NSExpansionAttributeName value:@(0.5) range:range];
    // 下劃線
    [attrStr addAttribute:NSUnderlineStyleAttributeName value:@(1) range:range];
    [attrStr addAttribute:NSUnderlineColorAttributeName value:[UIColor blueColor] range:range];
    // 刪除線
    [attrStr addAttribute:NSStrikethroughStyleAttributeName value:@(1) range:range];
    [attrStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor greenColor] range:range];

    // 連體字
    [attrStr addAttribute:NSLigatureAttributeName value:@(1) range:range];


    // 設定顏色
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.942 green:0.611 blue:0.771 alpha:1.000] range:range];
    // 背景色
    [attrStr addAttribute:NSBackgroundColorAttributeName value:[UIColor colorWithRed:0.475 green:0.482 blue:0.942 alpha:1.000] range:range];

    // stroke
    [attrStr addAttribute:NSStrokeColorAttributeName value:[UIColor blueColor] range:range];
    [attrStr addAttribute:NSStrokeWidthAttributeName value:@(2) range:range];

    // 設定段落樣式
    [attrStr addAttribute:NSParagraphStyleAttributeName value:muParagraph range:range];

    // 文字方向
    [attrStr addAttribute:NSVerticalGlyphFormAttributeName value:@(1) range:range];
    [attrStr addAttribute:NSWritingDirectionAttributeName value:@[@(2),@(3)] range:range];


    // 陰影
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowOffset = CGSizeMake(2, 2);
    shadow.shadowColor = [UIColor orangeColor];
    shadow.shadowBlurRadius = 1;
    [attrStr addAttribute:NSShadowAttributeName value:shadow range:range];

    // 連結
    [attrStr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"http://www.jianshu.com/p/8f49c9c99b21"] range:range];

    // 文字中加圖片
    NSTextAttachment *attachment=[[NSTextAttachment alloc] initWithData:nil ofType:nil];

    UIImage *img=[UIImage imageNamed:@"test.png"];
    attachment.image=img;
    attachment.bounds=CGRectMake(0, 0, 20, 20);
    [attrStr addAttribute:NSAttachmentAttributeName value:attachment range:range];

    // 基準線偏移
    [attrStr addAttribute:NSBaselineOffsetAttributeName value:@(50) range:range];

    self.attTV.attributedText = attrStr;
}

3.TextView行距字間距的問題

同時遇到一個需求,TextView輸入的內容的行距字間距進行調整,這樣輸入一大段字會清楚一點。 
網上的方法是在- (void)textViewDidChange:(UITextView *)textView代理方法中根據text生成對應格式的attributedText
- (void)textViewDidChange:(UITextView *)textView{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineSpacing = 16;// 字型的行間距

    NSDictionary *attributes = @{

                                 NSFontAttributeName:[UIFont systemFontOfSize:17],

                                 NSParagraphStyleAttributeName:paragraphStyle,

                                 NSKernAttributeName : @(1.4f)
                                 };

    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}

但是中文輸入法的時候就會懵逼,會同時打出英文

最後沒辦法,改成視覺化的textView,調整行距的屬性,字間距就沒辦法了,誰有好辦法可以教教我