在项目中经常会用到进行图文混排的展示一下界面,本文介绍使用UIWebVIew加载渲染过的HTML文档来实现这种需求.
基本原理:
生成HTML模版文件
具体样式需要根据需求实际编写.本文样例如下
1 | <!DOCTYPE html> |
注意:
1 | {{littleText}}和{{bigText}}就是后面要被实际数据进行替换的一个占位标识. |
先看看使用UIWebView加载未经渲染过效果
1 | // // ViewController.m // HTML渲染 // // Created by Alexcai on 15/7/7. // Copyright (c) 2015年 zhidier. All rights reserved. // #import "ViewController.h" #import "MGTemplateEngine.h" #import "ICUTemplateMatcher.h" @interface ViewController () <MGTemplateEngineDelegate> @property (weak, nonatomic) IBOutlet UIWebView *htmlWebview; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 获取html文件的路径 NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"Template" ofType:@"html"]; // 获取html模版文件内容 NSString *htmlString = [[NSString alloc]initWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil]; // 使用webview加载模版文件 [self.htmlWebview loadHTMLString:htmlString baseURL:nil]; } |
- 运行效果
使用模版引擎加载数据
实际开发中,数据一般多数情况都来自网络,本文使用本地假数据仅做效果演示用,供学习参考而已.
1 | @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.htmlWebview loadHTMLString:[self htmlStringWithMGTEngine] baseURL:nil]; } - (NSString *)htmlStringWithMGTEngine{ // 获取html文件的路径 NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"Template" ofType:@"html"]; // 创建MGT模版引擎对象 MGTemplateEngine *engine = [MGTemplateEngine templateEngine]; // 设置引擎匹配属性 [engine setMatcher:[ICUTemplateMatcher matcherWithTemplateEngine:engine]]; // 替换html文件中的bigText 字段为 come for MGT [engine setObject:@"come for MGT" forKey:@"bigText"]; // 替换html文件中的littleText 字段为 come also from MGTE [engine setObject:@"come also from MGTE" forKey:@"littleText"]; // 返回已经替换好的html return [engine processTemplateInFileAtPath:htmlPath withVariables:nil]; } @end |
运行效果
补充
MGTemplateEngine
在导入工程后,需要手动添加Foundation框架和UIKit框架如果需要在使用引擎拼装数据之后再做些处理工作,可以通过设置控制器为引擎的代理,然后通过代理方法:
(void)templateEngine:(MGTemplateEngine *)engine blockEnded:(NSDictionary *)blockInfo;
执行后续的操作即可.
注意
- HTML模版中的占位标识写法不要随意更改,固定写法为:
1
{{占位标识}}
- setObject 不要写成 setValue,否则导致工程运行崩溃.
后续(未完)
本文仅是MGTemplateEngine引擎的基本用法,还可以自定义匹配和过滤的条件,功能丰富,待深入研究后再做讨论.
另一种渲染引擎(下一篇文档再做介绍~)