iOS小知识:HTML字符串与富文本互转

3,830 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

引言

应用场景:使用原生视图UILabel显示服务端返回的带有HTML标签的内容

I 、 html转换为富文本

    NSString *html = @"<p style='color:green'>博客<span style='color:#e83c36;'><a>https://kunnan.blog.csdn.net/<a/></span><br/>微信公众号:<span style='color:red'>iOS逆向</span><br/>“订阅”一次 ,享受终身服务的快乐。</br><span style='color:red'>专注《iOS应用逆向与安全》</span>(包括iOS基础)</p>";
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

在这里插入图片描述

II、富文本转换为html

- (void)NSAttributedStringtohtmlWith:(NSAttributedString*)attStr{
    
    NSDictionary *dic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUnicodeStringEncoding)};
    
    
    NSData *data = [attStr dataFromRange:NSMakeRange(0, attStr.length) documentAttributes:dic error:nil];
    
    
    
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
    
    NSLog(@"NSAttributedStringtohtmlWith:%@",str);
    
    [self gotoAXWebViewControllerWithHtmlstr:str];

    
    

}

公众号:iOS逆向

III、加载本地HTML文件

1、文章:kunnan.blog.csdn.net/article/det… 2、原理:`使用[_webView loadHTMLString:html baseURL:baseURL]; 进行代码加载

    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
        [self loadHTMLString:_HTMLString baseURL:_baseURL];

`

  • 例子
#import <AXWebViewController/AXWebViewController.h>

- (void)gotoAXWebViewControllerWithHtmlstr:(NSString*)html{
    
    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];

    AXWebViewController *webVC = [[AXWebViewController alloc] initWithHTMLString:html baseURL:baseURL];

    UINavigationController *tmp = [[UINavigationController alloc]initWithRootViewController:webVC];


    
    webVC.showsToolBar = NO;
    webVC.navigationController.navigationBar.translucent = NO;
    webVC.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.100f green:0.100f blue:0.100f alpha:0.800f];
    webVC.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.996f green:0.867f blue:0.522f alpha:1.00f];
        //webVC.navigationType = AXWebViewControllerNavigationToolItem;
//    webVC.showsToolBar = YES;


    
    [self presentViewController:tmp animated:YES completion:^{
        
    } ];

}

see also

更多内容请关注#小程序:iOS逆向,只为你呈现有价值的信息,专注于移动端技术研究领域。

download.csdn.net/download/u0…

公众号:iOS逆向