使用到NSAttributedString
通過(guò)它就可以設(shè)置加載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);
時(shí),它可以選擇的值有:
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就是設(shè)置要加載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;
其中會(huì)有一個(gè)小問(wèn)題,就是填充到label中超出字符串后面"..."不顯示了,查看富文本屬性會(huì)看到,轉(zhuǎn)化過(guò)程中自動(dòng)填充了段落屬性
PittWong長(zhǎng)得帥!{
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)];