使用到NSAttributedString
通过它就可以设置加载HTML。iOS7之后才可以使用:
- (nullableinstancetype)initWithData:(NSData *)dataoptions:(NSDictionary<NSString *, id> *)options
documentAttributes:(NSDictionary<NSString *, id> * __nullable* __nullable)dict
error:(NSError **)errorNS_AVAILABLE(10_0, 7_0);
其中,options中的指定key为:
UIKIT_EXTERN NSString * const NSDocumentTypeDocumentAttribute NS_AVAILABLE(10_0, 7_0);
时,它可以选择的值有:
UIKIT_EXTERN NSString * const NSPlainTextDocumentType NS_AVAILABLE(10_0, 7_0);
UIKIT_EXTERN NSString * const NSRTFTextDocumentType NS_AVAILABLE(10_0, 7_0);
UIKIT_EXTERN NSString * const NSRTFDTextDocumentType NS_AVAILABLE(10_0, 7_0);
UIKIT_EXTERN NSString * const NSHTMLTextDocumentType NS_AVAILABLE(10_0, 7_0);
其中,NSHTMLTextDocumentType就是设置要加载HTML了。
NSData *data = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSAttributedString *html = [[NSAttributedString alloc]initWithData:data
options:options
documentAttributes:nil
error:nil];
self.htmlLabel.attributedText = html;
其中会有一个小问题,就是填充到label中超出字符串后面"..."不显示了,查看富文本属性会看到,转化过程中自动填充了段落属性
PittWong长得帅!{
NSColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSFont = "<UICTFont: 0x7f90d56a49b0> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 15/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSStrokeWidth = 0;
}他啦啦啦啦{
NSColor = "kCGColorSpaceModelRGB 1 0 0 1 ";
NSFont = "<UICTFont: 0x7f90d56a49b0> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 15/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 1 0 0 1 ";
NSStrokeWidth = 0;
}
移除段落属性...就能正常显示了
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithAttributedString: html];
[string removeAttribute:NSParagraphStyleAttributeName range: NSMakeRange(0, string.length)];