美文网首页
对关键字着色

对关键字着色

作者: 其实也没有 | 来源:发表于2016-07-18 16:45 被阅读26次

    http://www.cnblogs.com/wupei/p/4019963.html

    /**

    *  对指定内定进行着色,keywords数组与colors数组相对应

    *

    *  @param content  全部内容

    *  @param keyWords 关键字数组

    *  @param color    关键字对应颜色,如果传空,则默认对关键字着红色

    *  @param repeat   关键字出现多次的时候,是否全部进行多次着色,默认否

    *

    *  @return

    */

    +(NSAttributedString*)attributeStringWithContent:(NSString*)content keyWords:(NSArray*)keyWords colors:(NSArray*)colors repeat:(BOOL)repeat;

    +(NSAttributedString*)attributeStringWithContent:(NSString*)content keyWords:(NSArray*)keyWords colors:(NSArray*)colors repeat:(BOOL)repeat

    {

    NSMutableAttributedString*attString = [[NSMutableAttributedStringalloc] initWithString:content];

    if(keyWords) {

    [keyWords enumerateObjectsUsingBlock:^(idobj,NSUIntegeridx,BOOL*stop) {

    NSMutableString*tmpString=[NSMutableStringstringWithString:content];

    NSRangerange=[content rangeOfString:obj];

    NSIntegerlocation=0;

    while(range.length>0) {

    UIColor *color=nil;

    if(!colors[idx]) {

    color=[UIColor redColor];

    }else{

    color=colors[idx];

    }

    [attString addAttribute:(NSString*)NSForegroundColorAttributeNamevalue:color range:NSMakeRange(location+range.location, range.length)];

    location+=(range.location+range.length);

    NSString*tmp= [tmpString substringWithRange:NSMakeRange(range.location+range.length, content.length-location)];

    tmpString=[NSMutableStringstringWithString:tmp];

    range=[tmp rangeOfString:obj];

    if(!repeat) {

    break;

    }

    }

    }];

    }

    returnattString;

    }

    content是根据网址获得的网页源码字符串

    - (NSString*)changeToString:(NSString*)content{NSRegularExpression*regularExpretion=[NSRegularExpressionregularExpressionWithPattern:@"<[^>]*>|\n"options:0error:nil];        content = [regularExpretion stringByReplacingMatchesInString:content options:NSMatchingReportProgressrange:NSMakeRange(0, content.length) withTemplate:@"-"];//  替换所有html和换行匹配元素为"-"regularExpretion = [NSRegularExpressionregularExpressionWithPattern:@"-{1,}"options:0error:nil] ;    content = [regularExpretion stringByReplacingMatchesInString:content options:NSMatchingReportProgressrange:NSMakeRange(0, content.length) withTemplate:@"-"];//  把多个"-"匹配为一个"-"//  根据"-"分割到数组NSArray*arr=[NSArrayarray];    content = [NSStringstringWithString:content];    arr =  [content componentsSeparatedByString:@"-"];NSMutableArray*marr=[NSMutableArrayarrayWithArray:arr];    [marr removeObject:@""];NSMutableString*string = [[NSMutableStringalloc] init];for(inti =0; i < arr.count; i++) {        [string appendString:[NSStringstringWithFormat:@"%@",arr[i]]];    }returnstring;}

    相关文章

      网友评论

          本文标题:对关键字着色

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