UIKit 控件显示 HTML 标签渲染元素
引言
我们在实际的开发项目中,可能会用到渲染字体的情况,比如说字体的颜色、大小等相关信息,这些技术我们都可以轻松的借助 HTML 标签来实现。
显示 HTML 标签
该方法用于改变字体以及字体大小1
2//将 HTML 内容添加到单个字符串中
NSString * htmlStr = [NSString stringWithFormat:@"<span style=\"font-family:%@; font-size:%f\">%@</span>", fontName, fontSize, html];
将 HTML 内容进行显示 (建议将其封装成某个类别,比如 UILabel)1
2
3
4- (void)setHTMLWithStr:(NSString *)str{
str = [str stringByAppendString:[NSString stringWithFormat:@"<style>body{font-family:%@; font-size:%lfpx;}</sytle>", self.font.fontName, self.font.pointSize]];
self.attributedText = [NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
}