遇到一些服务器已经写好的html格式字符串,苦于webView的高度不好控制,发现用NSAttributedString很方便,推荐一下
oc
NSString * htmlString = @"<p><span style=\\"border: 1px solid rgb(0, 0, 0);\\"><em>好,真心好</em></span></p>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * myLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
myLabel.attributedText = attrStr;
[self.view addSubview:myLabel];
swift
let htmlString = self.bookModel.introduction
// let attrStr = NSAttributedString(data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes:nil)
let attrStr = try! NSAttributedString(
data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding)!,
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
documentAttributes: nil)
print("\\(attrStr)")
introductionView.textLabel.attributedText = attrStr