iOS通过html模版实现富文本编辑

来源:互联网 发布:fx网络什么意思 编辑:程序博客网 时间:2024/05/22 04:31

 在iOS开发中,常常会遇到一些富文本编辑,如新闻,公告等,NSMutableAttributedString又有一定的局限性,所以我想到用html 模版去加载富文本页面,根据所需要的格式,去构建相应的html界面。一个简单的html模版如下:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <link rel="stylesheet"href="mystyle.css"type="text/css">

    <style type="text/css">

        .sourceAndTime{

            width:100%;

            font-size:12pt;

            line-height:40px;

            color:#1b6761;

            padding-right:8px;

            padding-left:8px;

        }

        #news_title{

            font-weight:bold;

            font-size:20pt!important;

            padding-right:8px;

            padding-left:8px;

            color:#57918b

        }

        #container{

            font-size:$contentfontsize;

            text-indent:1em;

            padding-right:8px

            padding-left:8px;

        }

    </style>

</head>

<body style="margin-left:10px;border: 0;">

<div >

    <div id="news_title">$title</div>

    <div class='sourceAndTime'>

        <span>$time</span>

        <span style="padding-right:10px; float: right" >$source</span>

    </div>

</div>

<div style="width: 100%;margin: 0 auto;height: auto;" >

    <p style="text-align: center">

        <img  src=$imgSrcstyle="width: 50%;height:auto" />

    </p>

</div>

<div id="container">$content</div>

<br/><br/><br/><br/>

</body>

</html>

在模版中预留相应的唯一标志符,如$imgSrc等,然后在iOS端将这个html模版转换为一个字符串,然后再去替代这个字符串内的那些唯一标志符,具体iOS代码如下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"news_detail" ofType:@"html"];

  _webString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    _webString = [_webString stringByReplacingOccurrencesOfString:@"$title"withString:[_titleArray objectAtIndex:indexPath.row]];
    _webString = [_webString stringByReplacingOccurrencesOfString:@"$time" withString:[CNotificationVC TimeformatFromSeconds:[[ _timeArray objectAtIndex:indexPath.row] longLongValue]]];
    _webString = [_webString stringByReplacingOccurrencesOfString:@"$imgSrc"withString:[_imageArray objectAtIndex:indexPath.row]];
    _webString = [_webString stringByReplacingOccurrencesOfString:@"$content"withString:[_contentArray objectAtIndex:indexPath.row]];
    _webString = [_webString stringByReplacingOccurrencesOfString:@"$source" withString:[_adminArray objectAtIndex:indexPath.row]];

    UIWebView *webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,64,self.view.frame.size.width,self.view.frame.size.height)];

    webView.delegate =self;

    

    [webView setBackgroundColor:[UIColorclearColor]];

    [webView setOpaque:NO];

    [webView loadHTMLString:_webStrbaseURL:[NSURLfileURLWithPath:[[NSBundlemainBundle]pathForResource:@"news_detail"ofType:@"html"]]];    

    [self.viewaddSubview:webView];


具体步骤就是如此,希望对大家有所帮助
0 1
原创粉丝点击