我正在构建一个简单的 HTML 到 NSAttributedString 的转换方法,由于某种原因,NSScanner 类在找到标签后丢弃了一个空格。例如,如果 html 格式的字符串是@"This is a <b>bold</b> word"
,则结果是 @"This is a boldword"。为什么我的方法会丢失结束标签后面的空格?你觉得我的方法有什么可疑之处吗?
+ (NSAttributedString *)attributedStringFromHtmlString:(NSString *)htmlString {
NSMutableAttributedString *attributedString;
NSRange range;
NSScanner *htmlScanner;
NSMutableString *strippedString;
BOOL boldFlag = NO;
BOOL italicFlag = NO;
BOOL underlineFlag = NO;
htmlScanner = [NSScanner scannerWithString:htmlString];
while (![htmlScanner isAtEnd]) {
NSString *firstPass, *tagString;
NSCharacterSet *openTagSet;
NSCharacterSet *closeTagSet;
NSMutableAttributedString *newAttributedString;
openTagSet = [NSCharacterSet characterSetWithCharactersInString:@"<"];
closeTagSet = [NSCharacterSet characterSetWithCharactersInString:@">"];
newAttributedString = [[NSMutableAttributedString alloc] init];
if ([htmlScanner scanUpToCharactersFromSet:openTagSet intoString:&firstPass]) {
[newAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:firstPass]];
[attributedString appendAttributedString:newAttributedString];
}
// Either we hit a '<' or we're at the end of the text.
if (![htmlScanner isAtEnd]) {
[htmlScanner scanCharactersFromSet:openTagSet intoString:NULL];
[htmlScanner scanUpToCharactersFromSet:closeTagSet intoString:&tagString];
[htmlScanner scanCharactersFromSet:closeTagSet intoString:NULL];
tagString = [tagString lowercaseString];
if ([tagString isEqual:@"b"]) {
boldFlag = YES;
}
else if ([tagString isEqual:@"/b"]) {
boldFlag = NO;
}
else if ([tagString isEqual:@"h"]) {
boldFlag = YES;
}
else if ([tagString isEqual:@"/h"]) {
boldFlag = NO;
}
else if ([tagString isEqual:@"i"]) {
italicFlag = YES;
}
else if ([tagString isEqual:@"/i"]) {
italicFlag = NO;
}
else if ([tagString isEqual:@"br /"]) {
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
}
}
}
range.location = 0;
range.length = [attributedString length];
return attributedString;
}
提前感谢您的智慧!