SDK提供的文本控件
- UILabel(繼承UIView):無法輸入伐蒋;
- UITextField(繼承UIView):只能輸入一行闷板,不可以滾動(dòng)运杭,可以設(shè)置提醒文字侦铜;
- UITextView(繼承UIScrollView):能輸入多行专甩,可以滾動(dòng),不可以設(shè)置提醒文字钉稍。
三個(gè)控件都支持attributedText涤躲,進(jìn)而都可以直接原生顯示html,具體代碼如下:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding]
options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes:nil
error:nil];
特性:text和html風(fēng)格統(tǒng)一
很多情況下贡未,一個(gè)控件可能既要可以顯示text种樱,也要可以顯示html蒙袍,而它們的默認(rèn)風(fēng)格屬性都一樣。為了問題的簡單化嫩挤,這里只討論UILabel害幅。大家都知道UILabel的font和textColor屬性只對text起作用,對attributedText不起作用岂昭,如果讓后臺(tái)或者前端區(qū)分text或者h(yuǎn)tml以现,也是很蛋疼的一件事。
利用html的標(biāo)簽约啊,在content外面封裝一層默認(rèn)屬性邑遏。
瀏覽一下html常用標(biāo)簽,可發(fā)現(xiàn)span標(biāo)簽可以勝任該工作恰矩,具體代碼如下:
+ (NSAttributedString *)attributedStringContent:(NSString *)content
{
content = [NSString stringWithFormat:@"<span style=\"color:#8d8b8b; font-size:15px\">%@</span>", content];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding]
options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes:nil
error:nil];
return attributedString;
}