美文网首页2022年实践iOS经验总结iOS沉淀
iOS富文本(NSAttributedString)UIText

iOS富文本(NSAttributedString)UIText

作者: 文子飞_ | 来源:发表于2020-06-17 12:01 被阅读0次

    项目上要加载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;
    
    
    附件

    这个我的也没显示出来,想钻研的看这里http://www.jianshu.com/p/5babe8b7983e

        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;
    }
    
    

    我的效果图很磕馋

    image

    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,调整行距的属性,字间距就没办法了,谁有好办法可以教教我

    image

    结束... 看在苦劳点个赞😢



    《拼接加载HTML标签文本》

    NSString *content = [NSString stringWithFormat:@"%@",article_msg[@"content"]];
                NSString *title = [NSString stringWithFormat:@"%@",article_msg[@"title"]];
                NSString *pubtime = [NSString stringWithFormat:@"%@",article_msg[@"pubtime"]];
                NSString *clicknum = [NSString stringWithFormat:@"%@人已读",article_msg[@"clicknum"]];
                NSString *pubtime_clicknum = [NSString stringWithFormat:@"%@ | %@", pubtime, clicknum];
                //NSLog(@"dataStr===%@",dataStr);
                //NSString *htmlString = [NSString stringWithFormat:@"%@%@%@",@"<head><style>img{max-width:",[NSString stringWithFormat:@"%f%@",kScreenWidth - 8 * kScreenWidthProportion * 2,@"!important;}</style></head>"], dataStr];
                //html <head></head>
                
                NSString *string1 = [NSString stringWithFormat:@"<head><h2>%@</h2>%@<style>img{max-width:", title, pubtime_clicknum];
                NSString *string2 = [NSString stringWithFormat:@"%f%@", kScreenWidth - 8 * kScreenWidthProportion * 2,@"!important;}</style></head><br></br><br></br><br></br>"];
                //html <body></body>
                NSString *string3 = content;
                
                NSString *htmlString = [NSString stringWithFormat:@"%@%@%@", string1,string2, string3];
                
                
                
                NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
                
                // 设置颜色
                NSRange range = NSMakeRange(title.length, pubtime_clicknum.length + 1);
                [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
                
                contentTextView.attributedText = attributedString;
                contentTextView.height = [self heightForString:contentTextView andWidth:(kScreenWidth - 8 * kScreenWidthProportion * 2)];
                contentTextView.contentSize = CGSizeMake(kScreenWidth - 8 * kScreenWidthProportion * 2, contentTextView.height);
                
                if (contentTextView.height < (kScreenHeight - kHeaderHeight)) {
                    mainScrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight - kHeaderHeight);
                }else{
                    mainScrollView.contentSize = CGSizeMake(kScreenWidth, contentTextView.maxY);
                }
    



    《NSAttributedString+YYText分类富文本使用》

    /// UITextView、UITextField的 NSAttributedString富文本
    - (void)testyy_MutableAttributedString {
        
        NSString *contentStr = @"\n      欢迎使用XXXAPP!\n\n      在使用我们的产品和服务前,请先阅读并了解《XXX用户注册协议》和《法律声明以及隐私协议》\n\n    我们将严格按照上述协议为你提供服务,保护你的信息安全,点击“同意”即表示你已阅读并同意全部条款";
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:contentStr];
        attributedString.yy_lineSpacing = 8;
        attributedString.yy_font = SYSTEMFONT(17);
        
        NSRange registRange = [contentStr rangeOfString:@"《XXX用户注册协议》"];
        [attributedString yy_setTextHighlightRange:registRange color:UIColorHex(#0AB0ED) backgroundColor:KWhiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            NSString *url = @"";
            BaseWebViewController *webViewController = [[BaseWebViewController alloc] initWithUrl:url];
            [self.navigationController pushViewController:webViewController animated:YES];
        }];
        
        NSRange privacyRange = [contentStr rangeOfString:@"《法律声明以及隐私协议》"];
        [attributedString yy_setTextHighlightRange:privacyRange color:UIColorHex(#0AB0ED) backgroundColor:KWhiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            NSString *url = [NSString stringWithFormat:@"%@%@", [APPConfigManager shareAPPConfigManager].userMobileH5Host, PrivacyAgreementWebPath];
            BaseWebViewController *webViewController = [[BaseWebViewController alloc] initWithUrl:url];
            [self.navigationController pushViewController:webViewController animated:YES];
        }];
        
        self.contentTextView.attributedText = attributedString;
        self.testTextField.attributedText = attributedString;
        
    }
    

    《NSAttributedString设置多个颜色》

    
    - (void)testAddAttribute {
        
        NSString *amountColor = [NSString stringWithFormat:@"%.2f", self.beforeModel.rateAwardAmount.floatValue];
        NSString *payLcsfeeColor = [NSString stringWithFormat:@"%.2f", self.beforeModel.payLcsfee.floatValue];
    
        // %@前加个空格,防止2个值一样时,第2个设置不了
        NSString *titleString = [NSString stringWithFormat:@"含好评返现金 %@元,代付运费 %@元", amountColor, payLcsfeeColor];
        NSMutableAttributedString * attrbuteString = [[NSMutableAttributedString alloc] initWithString:titleString];
        
        // 1、attrbuteString,addAttribute设置颜色
        [attrbuteString addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xFF8850) range:[titleString rangeOfString:amountColor]];
        [attrbuteString addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xFF8850) range:[titleString rangeOfString:payLcsfeeColor]];
        
        if (self.beforeModel.platformServiceFee.floatValue > 0) {
            // 2、拼接attrbuteString
            [attrbuteString appendAttributedString:[self platformServiceFeeAttrbuteString]];
        }
        
        // 3、attrbuteString,addAttribute设置段落
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineSpacing = 5; // 行间距
        [attrbuteString addAttributes:@{
            NSParagraphStyleAttributeName: paragraphStyle
        } range:NSMakeRange(0, attrbuteString.string.length)];
        
        // 4、attrbuteString赋值
        self.moneyLab.attributedText = attrbuteString;
    }
    
    /// 平台服务费AttributedString
    - (NSMutableAttributedString *)platformServiceFeeAttrbuteString {
        NSString *colorString = [NSString stringWithFormat:@"%.2f", self.beforeModel.platformServiceFee.floatValue];
        NSString *platformServiceFee = [NSString stringWithFormat:@",平台服务费%@元", colorString];
        NSMutableAttributedString *attrbuteString = [[NSMutableAttributedString alloc] initWithString:platformServiceFee];
        [attrbuteString addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xFF8850) range:[platformServiceFee rangeOfString:colorString]];
        return attrbuteString;
    }
    
    

    相关文章

      网友评论

        本文标题:iOS富文本(NSAttributedString)UIText

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