在開發中,我們加載HTML最常用的是UIWebView,其實UITextView也可以加載HTML代碼。
- (void)viewDidLoad {
[super viewDidLoad];
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, kScreenHeight - 50)];
[self.view addSubview:textView];
//HTML代碼
NSString *htmlStr = @"
<img src=\"http://img0.imgtn.bdimg.com/it/u=1368418777,3304551799&fm=21&gp=0.jpg\"
hiuehuirhfiefguihuiefuwifhewufcehsifhoifhiofhwohfwiohfwoicehicehiheifjkhuhuihwefhuiwhfibfiwehfurwhfuiwhfuiwefhuirwhfiw
<img src=\"http://img0.imgtn.bdimg.com/it/u=331456922,2614791273&fm=21&gp=0.jpg\"
hviurhrihvuerhviohvoiwehvewiohiowhviowvhoiheiohihuihguguygigdusichvregtgtgegtgvrtvtrbtrbtrbtrbtrbtbtvrgeggergrbrt<img src=\"http://img3.imgtn.bdimg.com/it/u=3236147722,3184690082&fm=21&gp=0.jpg\"
hiuehuirhfiefguihuiefuwifhewufcehsicehicehiheifjkhuhuihwefhuiwhfibfiwehfurwhfuiwhfuiwefhuirwhfiw
";
//對圖片大小進行處理,適應屏幕寬度
NSString *newString = [htmlStr stringByReplacingOccurrencesOfString:@"<img" withString:[NSString stringWithFormat:@"<img width=\"%f\"",kScreenWidth - 10]];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[newString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;
}
注意:在info.plist中配置:
<key>App Transport Security Settings</key>
<dict>
<key>Allow Arbitrary Loads</key>
<true/>
</dict>
注:
// 當前屏幕寬度
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
// 當前屏幕高度
#define kScreenHeight [UIScreen mainScreen].bounds.size.height