美文网首页
iOS NSMutableAttributedString 富文

iOS NSMutableAttributedString 富文

作者: Andy_Swift | 来源:发表于2016-08-12 19:41 被阅读145次

    NSMutableAttributedString是iOS自带的富文本类,通过使用该类,可以方便地为设置文本的阴影、删除线、段落格式等属性,也可以实现简单的图文混排功能。

    1、NSMutableAttributedString常见的属性:
    字体 <i>NSFontAttributeName</i>
    阴影 <i>NSShadowAttributeName</i>
    段落格式 <i>NSParagraphStyleAttributeName</i>
    字体颜色 <i>NSForegroundColorAttributeName</i>
    背景颜色 <i>NSBackgroundColorAttributeName</i>
    删除线格式 <i>NSStrikethroughStyleAttributeName</i>
    下划线格式 <i>NSUnderlineStyleAttributeName</i>
    删除线颜色 <i>NSStrokeColorAttributeName</i>
    删除线宽度 <i>NSStrokeWidthAttributeName</i>

    2、根据属性字典创建富文本字符串,代码如下:

    NSDictionary *dict = @{
                           NSFontAttributeName  :[UIFont systemFontOfSize:15.0],
                           NSForegroundColorAttributeName   :[UIColor redColor],
                           NSBackgroundColorAttributeName :[UIColor greenColor]
                           };
    NSString *str = @"This is a mutable attributed string ...";
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str attributes:dict];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 200, 40)];
    label.attributedText = attrStr;
    [self.view addSubview:label];
    

    3、编辑某一范围内富文本文字的属性常见方法及应用
    附查询 <b>字符串A在字符串B中的range</b>

        NSString *strA = @"会当凌绝顶,一览众山小。";
        NSString *StrB = @"众山";
        NSRange range = [strA rangeOfString:StrB];
    

    a. 为某一范围内文字设置多个属性
    <i>- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;</i>

    b. 为某一范围内文字添加某个属性
    <i>- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;</i>

    c. 为某一范围内文字添加多个属性
    <i>- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;</i>

    d. 移除某范围内的某个属性
    <i>- (void)removeAttribute:(NSString *)name range:(NSRange)range;</i>

    4、为富文本中添加图片内容

        NSTextAttachment *attch = [[NSTextAttachment alloc] init];
        // 图片
        attch.image = [UIImage imageNamed:@"imgName"];
        attch.bounds = CGRectMake(10, 0, 50, 50);
        NSAttributedString *string = [NSAttributedString     attributedStringWithAttachment:attch];
        [str appendAttributedString:string];
        label.attributedText = str;
    

    str为文字内容,富文本支持图片插入到文字文本到任何位置。

    更多方法和属性说明详见苹果官方说明文档:
    https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html#//apple_ref/doc/uid/TP40003689

    相关文章

      网友评论

          本文标题:iOS NSMutableAttributedString 富文

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