iOS 控件显示网页代码

UITextView,UIWebView 直接显示html代码

方法 1

////获取html到NSString
NSURL *url = [NSURL URLWithString:@"http://www.xtox.net/product/detail.action?product.id=11"];
NSString *strHtml = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
////显示到UIWebView
[self.m_web loadHTMLString:strHtml baseURL:nil];
/////显示到UITextView
[self.m_TextView setContentToHTMLString:strHtml];

方法 2

//对图片大小进行处理,适应屏幕宽度
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;

UILabel 的网页代码显示

// ios 7.0以后才能使用
NSData *data = [model.html dataUsingEncoding:NSUnicodeStringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSAttributedString *html = [[NSAttributedString alloc]initWithData:data
                                                            options:options
                                                 documentAttributes:nil
                                                              error:nil];
self.htmlLabel.attributedText = html;