小编Mar*_*bar的帖子

将嵌套的粗体斜体HTML标记转换为NSAttributedString

我使用此代码使用RegEx将HTML字符串转换为NSAttributedString.我唯一的问题是嵌套的粗体和斜体标签.RegEx是正确的方法吗?

另外,我想避免使用HTML解析器,因为我需要的只有Bold,Italic和Underline属性以及StrikeThrough(如果可能).

有什么建议?

- (NSMutableAttributedString *)applyStylesToString:(NSString *)string searchRange:(NSRange)searchRange {

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    [attributedString addAttribute:NSFontAttributeName value:[StylesConfig regularLargeFont] range:searchRange];

    NSDictionary *boldAttributes = @{ NSFontAttributeName : [StylesConfig regularBoldLargeFont] };
    NSDictionary *italicAttributes = @{ NSFontAttributeName : [StylesConfig regularItalicLargeFont] };
    NSDictionary *underlineAttributes = @{ NSUnderlineStyleAttributeName : @1};
    NSDictionary *strikeThroughAttributes = @{ NSStrikethroughStyleAttributeName : @1};

    NSDictionary *replacements = @{
                                   @"<b>(.*?)</b>" : boldAttributes,
                                   @"<i>(.*?)</i>" : italicAttributes,
                                   @"<u>(.*?)</u>" : underlineAttributes,
                                   @"<s>(.*?)</s>" : strikeThroughAttributes
                                   };

    for (NSString *key in replacements) {

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:key …
Run Code Online (Sandbox Code Playgroud)

html attributes objective-c nsattributedstring ios

2
推荐指数
1
解决办法
1496
查看次数

标签 统计

attributes ×1

html ×1

ios ×1

nsattributedstring ×1

objective-c ×1