我正在尝试获取一个格式为html的文本片段,以便在UITableViewCell中的iPhone上很好地显示.
到目前为止我有这个:
NSError* error;
NSString* source = @"<strong>Nice</strong> try, Phil";
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&error];
Run Code Online (Sandbox Code Playgroud)
这种作品.我得到一些粗体'好'的文字!但是......它还将字体设置为Times Roman!这不是我想要的字体.我想我需要在documentAttributes中设置一些内容,但是,我无法在任何地方找到任何示例.
现在iOS 6中完全支持NSAttributedString,是否有一个库将采用带有markdown的NSString,并将其转换为NSAttributedString?
我UITextView在其中使用我显示NSAttributedString.我从服务器获得HTML字符串.我使用下面的代码将HTML转换为NSAttributedString.
NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc]initWithData:[strHTML dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
Run Code Online (Sandbox Code Playgroud)
要应用字体,我尝试了以下2个代码.
要应用属性我使用下面的代码.
[attrib addAttribute:NSFontAttributeName
value:myFont
range:NSMakeRange(0, attrib.length)];
Run Code Online (Sandbox Code Playgroud)
对于自定义字符串首先我在下面创建NSString,然后隐藏NSAttributedString
NSString *strHTML = [NSString stringWithFormat:@"<span style=\"font-family: myFont; font-size: 12\">%@</span>",@"my string"];
Run Code Online (Sandbox Code Playgroud)
使用两个代码字体已成功更改.但Bold和Italic未应用仅Underline应用于NSAttributedString.
我参考下面的链接.
对于链接3,我应该从服务器端应用字体和标签,然后检索HTML字符串?
任何帮助都会得到满足!
我有一个 textView,允许用户输入 NSAttributedString,转换为 html 字符串,然后存储到数据库中。我还有代码将 html 字符串转换回来并显示在 textView 中进行编辑。我的转换代码是
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
return html
}
}
extension NSAttributedString {
func htmlString() -> String? {
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
if let htmlString = String(data:htmlData, …Run Code Online (Sandbox Code Playgroud)