我正在尝试获得一个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];
这种方法很管用。我收到了一些用粗体显示“Nice”的文本!但是..。它还将字体设置为Times Roman!这不是我想要的字体。我想我需要在documentAttributes中设置一些东西,但是,我在任何地方都找不到任何示例。
发布于 2013-11-13 20:25:31
我想通了。有点像熊,也许不是最好的答案。
这段代码将经历所有的字体更改。我知道它使用的字体是"Times New Roman“和"Times New Roman BoldMT”。但不管怎样,这将找到粗体字体,并让我重新设置它们。我也可以重置大小,同时我在它。
我真的希望/认为有一种方法可以在解析时设置它,但是如果有的话,我找不到它。
NSRange range = (NSRange){0,[str length]};
[str enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
UIFont* currentFont = value;
UIFont *replacementFont = nil;
if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound) {
replacementFont = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:25.0f];
} else {
replacementFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0f];
}
[str addAttribute:NSFontAttributeName value:replacementFont range:range];
}];
发布于 2014-12-11 19:58:49
#import "UILabel+HTML.h"
@implementation UILabel (HTML)
- (void)jaq_setHTMLFromString:(NSString *)string {
string = [string stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",
self.font.fontName,
self.font.pointSize]];
self.attributedText = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
}
@end
这样你就不需要指定你想要的字体,它将采用标签字体和大小。
发布于 2014-07-09 20:23:42
我实际上找到了这个问题的一个可行的解决方案:
在解析之前更改HTML响应字符串中的字体。
NSString *aux = [NSString stringWithFormat:@"<span style=\"font-family: YOUR_FONT_NAME; font-size: SIZE\">%@</span>", htmlResponse];
示例:
NSString *aux = [NSString stringWithFormat:@"<span style=\"font-family: HelveticaNeue-Thin; font-size: 17\">%@</span>", [response objectForKey:@"content"]];
Swift版本:
let aux = "<span style=\"font-family: YOUR_FONT_NAME; font-size: SIZE\">\(htmlResponse)</span>"
https://stackoverflow.com/questions/19921972
复制相似问题