为什么NSScanner会丢弃空白?

时间:2013-11-05 23:05:54

标签: ios cocoa-touch cocoa core-text

我正在为NSAttributedString转换方法构建一个简单的HTML,并且由于某种原因,NSScanner类在找到标记后丢弃了一个空格。例如,如果html格式的字符串是@"This is a <b>bold</b> word",则结果为@“这是一个粗体字”。为什么我的方法会在结束标记后丢失空格?你觉得我的方法有什么可疑之处吗?

+ (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;
}

提前感谢您的智慧!

1 个答案:

答案 0 :(得分:2)

因为NSScanner的charactersToBeSkipped的默认值是所有空格字符。

尝试将其设置为nil:

htmlScanner.charactersToBeSkipped = nil;