删除html标签并在UILabel中显示目标c
问题描述:
我正在获取& p>像我的api响应中的Html标签。我想在UILabel
删除html标签并在UILabel中显示目标c
我做了什么,以显示这些内容是:
NSString *STR_api = [NSString [email protected]:"%@",[API_res valueforkey:@"description"]];
STR_api = [STR_api StringByreplacingaccurancesofString @" " with [email protected]""];
我要的是,在它显示像大胆的门户网站,一段是有可能在的UILabel显示通过格式化以上响应
在此先感谢
答
我从完美的解决方案试图从Larme's answer
我得到了solution.It工作正常。
NSString *strHTML = @"S.Panchami 01.38<br>Arudra 02.01<br>V.08.54-10.39<br>D.05.02-06.52<br> <font color=red><u>Festival</u></font><br><font color=blue>Shankara Jayanthi<br></font>";
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[strHTML dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
NSLog(@"html: %@",strHTML);
NSLog(@"attr: %@", attrStr);
NSLog(@"string: %@", [attrStr string]);
NSString *finalString = [attrStr string];
NSLog(@"The finalString is - %@",finalString);
的印刷结果是
HTML
html: S.Panchami 01.38<br>Arudra 02.01<br>V.08.54-10.39<br>D.05.02-06.52<br> <font color=red><u>Festival</u></font><br><font color=blue>Shankara Jayanthi<br></font>
串
string: S.Panchami 01.38
Arudra 02.01
V.08.54-10.39
D.05.02-06.52
Festival
Shankara Jayanthi
最终的字符串
The finalString is - S.Panchami 01.38
Arudra 02.01
V.08.54-10.39
D.05.02-06.52
Festival
Shankara Jayanthi
现在从字符串除去& NBSP
OPTION 1
NSRange range;
while ((range = [finalString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
finalString = [finalString stringByReplacingCharactersInRange:range withString:@""];
OPTION 2
finalString = [finalString stringByReplacingOccurrencesOfString:@" " withString:@""];
+0
这是最好标记为重复然后.. – Larme
+0
但仍然 - 显示在我的标签其他标签走了.. :) –
答
试试这个代码:
NSString *strDescription = [NSString stringWithFormat:@"%@",[API_res valueforkey:@"description"]];
self.lblDescription.attributedText = [self getData:strDescription];
转换HtmlString串
-(NSAttributedString *)getData:(NSString *)str
{
NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
NSAttributedString *decodedString;
decodedString = [[NSAttributedString alloc] initWithData:stringData
options:options
documentAttributes:NULL
error:NULL];
return decodedString;
}
你可以用'NSAttributedString'解析HTML字符串,并以'UILabel'显示。 – Larme
[将iOS中的HTML转换为NSAttributedString]可能重复(http://stackoverflow.com/questions/4217820/convert-html-to-nsattributedstring-in-ios) – Larme
请问您能否让我看看您的HTML字符串? – user3182143