美文网首页iOS知识专题
iOS技术文档No.10 AppKit_NSAttributed

iOS技术文档No.10 AppKit_NSAttributed

作者: 孤独雪域 | 来源:发表于2017-07-21 17:12 被阅读24次

    在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。这些都可以用强大的NSMuttableAttstring实现。

    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;
    

    附件,图片

    参考iOS技术文档No.7 UIKit_NSTextAttachment为富文本添加图片
    NSTextAttachment *attachment=[[NSTextAttachment alloc] initWithData:nil ofType:nil];
    UIImage *img=[UIImage imageNamed:@"test.png"];
    attachment.image=img;
    attachment.bounds=CGRectMake(0, 0, 20, 20);
    NSAttributedString *text = [NSAttributedString attributedStringWithAttachment:attachment];
    如果你想要添加自定义view也请参考我的另一篇文章iOS技术文档No.7 UIKit_NSTextAttachment为富文本添加图片

    3.属性及方法

    /*
        NSAttributedString
    */
    @property (readonly, copy) NSString *string; // 无属性的字符串
    @property (readonly) NSUInteger length; // 字符串长度
     
    // 初始化方法
    - (instancetype)initWithString:(NSString *)str;
    - (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs;
    - (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
    // 等同性判断
    - (BOOL)isEqualToAttributedString:(NSAttributedString *)other;
    // 返回指定范围的属性
    - (NSDictionary<NSString *, id> *)attributesAtIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit;
    - (nullable id)attribute:(NSString *)attrName atIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit;
    // 遍历获得符合指定属性或属性字典的区域(range),并在 block 中进行设置
    - (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary<NSString *, id> *attrs, NSRange range, BOOL *stop))block;
    - (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(id __nullable value, NSRange range, BOOL *stop))block;
     
    /*
        NSMutableAttributedString
    */
    // 增加属性
    - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
    - (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
    - (void)setAttributedString:(NSAttributedString *)attrString;
    - (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
    // 删除属性
    - (void)removeAttribute:(NSString *)name range:(NSRange)range;
    // 插入 attributedString
    - (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc;
    - (void)appendAttributedString:(NSAttributedString *)attrString;
    // 替换 attributedString
    - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;
    - (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;
    

    代码

    self.attTV=[[UITextView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.attTV.backgroundColor=[UIColor whiteColor];
        [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:[@"我嫉妒你的爱气势如虹,像个人气高居不下的天后,你要的不是我而是一种虚荣,有人疼才显得多么出众" dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        
        
        NSRange range = NSMakeRange(0, attrStr.length);
        // 设置字体大小
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] 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:@"1"];
        attachment.image=img;
        attachment.bounds=CGRectMake(0, 0, 30, 30);
        NSAttributedString *image = [NSAttributedString attributedStringWithAttachment:attachment];
    //    [attrStr addAttribute:NSAttachmentAttributeName value:attachment range:range];
        [attrStr appendAttributedString:image];
        
        // 基准线偏移
        [attrStr addAttribute:NSBaselineOffsetAttributeName value:@(50) range:range];
        
        self.attTV.attributedText = attrStr;
    

    相关文章

      网友评论

        本文标题:iOS技术文档No.10 AppKit_NSAttributed

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