1. 程式人生 > >iOS通過html模版實現富文字編輯

iOS通過html模版實現富文字編輯

 在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];

具體步驟就是如此,希望對大家有所幫助