美文网首页
iOS将()中内容添加富文本

iOS将()中内容添加富文本

作者: 忧郁男生 | 来源:发表于2017-03-09 10:26 被阅读0次

    在项目中集成 regexkitlite 集成 网上有教程

    - (NSMutableAttributedString *)extractBracketsContentSelectAttrs:(NSDictionary *)selectAttr noSelectAttrs:(NSDictionary *)noSelectAttr{//字典为富文本

    NSString *str = [NSString stringWithString:self]; 

    NSString *regex = @"(?<=\\()(.+?)(?=\\))";//()正则

    NSArray *matchStrArr = [self componentsMatchedByRegex:regex];//regexkitlite提取()中内容可能有多个()返回数组

    str = [str stringByReplacingOccurrencesOfString:@"(" withString:@""];

    str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];

    NSRange remainRange = NSMakeRange(0, str.length);

    NSMutableArray *ranges = [[NSMutableArray alloc] initWithCapacity:matchStrArr.count];

    for (NSString *indexStr in matchStrArr) {

    NSRange firstRange =  [str rangeOfString:indexStr options:NSCaseInsensitiveSearch range:remainRange];

    NSValue * rangeValue = [NSValue valueWithRange:firstRange];

    [ranges addObject:rangeValue];

    NSUInteger endLocation = firstRange.location + firstRange.length;

    remainRange = NSMakeRange(endLocation, str.length - endLocation);

    }

    NSMutableAttributedString *mutableStr = [[NSMutableAttributedString alloc] initWithString:str];

    [mutableStr addAttributes:noSelectAttr range:NSMakeRange(0, mutableStr.length)];

    for (NSValue *value in ranges) {

    [mutableStr addAttributes:selectAttr range:value.rangeValue];

    }

    return mutableStr;

    }

    相关文章

      网友评论

          本文标题:iOS将()中内容添加富文本

          本文链接:https://www.haomeiwen.com/subject/wnkwgttx.html