iOS富文本

作者: 七里田间的守望者 | 来源:发表于2016-12-26 11:30 被阅读223次

    在iOS上能进行文本显示的控件有UILable,UITextField,UITextView。然而这些控件本身对文本的展现方式很单一,通常仅仅能够控制字体样式、大小、颜色、加粗、斜体等等,而对于行距控制,字距控制,段落控制等高级功能却无能为力。

    而iOS7的发布,苹果又引入了TextKit,TextKit是一个快速而又现代化的文字排版和渲染引擎。

    TextKit并没有新增类,只是在原有的文本显示控件上进行了封装,可以在平时我们最喜欢使用的UILabel,UITextField,UITextView等控件里面使用,其最主要的作用就是为程序提供文字排版和渲染的功能

    1、NSMutableAttributedString的基本使用

    富文本注意:
    先设置的先显示,后设置的,如果和先设置的样式不一致,是会覆盖的,富文本的设置具有先后顺序。
    不要忽略了空格也是一个字符。
    建议使用灵活的好用的NSMutableAttributedString,不要使用NSAttributedString。
    富文本基本使用方法的思路概要

    1、创建一个NSMutableAttributedString富文本对象(一般不用NSAttributedString)
    2、设置addAttribute属性
    (1) addAttribute: 一个属性
    (2) addAttributes: 一个存储多个属性的属性字典,比如这个字典可以是:
    NSDictionary *attrDic = @{
    NSFontAttributeName: [UIFont fontWithName: @"Zapfino" size: 15],
    NSForegroundColorAttributeName: [UIColor blueColor]
    };
    3、控件.attributedText = 富文本对象(和控件.txt = NSString文本对象不一样的)

    
        NSString * str = @"some text bula bula";
        
        //添加富文本对象
        NSMutableAttributedString * attr = [[NSMutableAttributedString alloc]initWithString:str];
        //设置字体颜色为红色
        [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 5)];
        //设置字体大小
        [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28] range:NSMakeRange(4, 5)];
        
        self.label.attributedText = attr;
    
    Paste_Image.png

    NSMutableAttributedString可以设置的属性有:

    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 对象
    

    2.NSTextAttachment图文混排简单应用

    
        //设置图片
        NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
        //设置图片属性
        attachment.image = [UIImage imageNamed:@"selected"];
        //设置图片的bounds
        attachment.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 180);
        //将attachment转换成字符串属性
        NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
        //把图片插入到文本中
        [self.textView.textStorage insertAttributedString:attachmentString atIndex:0];
    
    //也可以拼接到文本后面
    //    [self.textView.textStorage appendAttributedString:attachmentString];
    
    Paste_Image.png

    textview的实际使用

    • 实现的过程如下:
      storage --> layoutManager --> textContainer --> textView
    
        // 装载内容的容器
        NSTextStorage *storage = [NSTextStorage new];
        [storage replaceCharactersInRange:NSMakeRange(0, 0)
                               withString:
         @"未选择的路-弗罗斯特\n\n黄色的树林里分出两条路,\n可惜我不能同时去涉足,\n我在那路口久久伫立,\n我向着一条路极目望去,\n直到它消失在丛林深处。\n但我却选了另外一条路,\n它荒草萋萋,十分幽寂,\n显得更诱人、更美丽,\n虽然在这两条小路上,\n都很少留下旅人的足迹,\n虽然那天清晨落叶满地,\n两条路都未经脚印污染。\n啊,留下一条路等改日再见!\n但我知道路径延绵无尽头,\n恐怕我难以再回返。\n也许多少年后在某个地方,\n我将轻声叹息把往事回顾,\n一片树林里分出两条路,\n而我选了人迹更少的一条,\n从此决定了我一生的道路。"];
        
        // 给内容容器添加布局(可以添加多个)
        NSLayoutManager *layoutManager = [NSLayoutManager new];
        [storage addLayoutManager:layoutManager];
        
        // 带有内容和布局的容器
        NSTextContainer *textContainer = [NSTextContainer new];
        [layoutManager addTextContainer:textContainer];
        
        // 给TextView添加带有内容和布局的容器
        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];
    

    制作富文本,你可能会有一些定制的需求,比如图片的高度不想每个都要设置一边,你可以写一个继承,然后将下面方法重写

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

    替换文本内容里面的字符为图片

    
        //添加富文本对象
        NSMutableAttributedString * attachmentString = [[NSMutableAttributedString alloc]initWithString:str];
        //设置图片
        NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
        //设置图片属性
        attachment.image = [UIImage imageNamed:@"selected"];
        //设置图片的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.为某一范围内文字设置多个属性
    - (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
    为某一范围内文字添加某个属性
    - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
    
    为某一范围内文字添加多个属性
    - (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
    移除某范围内的某个属性
    - (void)removeAttribute:(NSString *)name range:(NSRange)range;
    
    label.lineBreakMode = NSLineBreakByCharWrapping;以字符为显示单位显示,后面部分省略不显示。
    label.lineBreakMode = NSLineBreakByClipping;剪切与文本宽度相同的内容长度,后半部分被删除。
    label.lineBreakMode = NSLineBreakByTruncatingHead;前面部分文字以……方式省略,显示尾部文字内容。
    label.lineBreakMode = NSLineBreakByTruncatingMiddle;中间的内容以……方式省略,显示头尾的文字内容。
    label.lineBreakMode = NSLineBreakByTruncatingTail;结尾部分的内容以……方式省略,显示头的文字内容。
    label.lineBreakMode = NSLineBreakByWordWrapping;以单词为显示单位显示,后面部分省略不显示。
    

    相关文章

      网友评论

        本文标题:iOS富文本

        本文链接:https://www.haomeiwen.com/subject/csljvttx.html