首页 > 移动平台 > 详细

iOS中NSAttributedString的使用--对关键字着色,以及处理html实例

时间:2014-10-12 00:15:48      阅读:305      评论:0      收藏:0      [点我收藏+]

      1,最近项目中用到了一个功能,一个很好的功能。就是用户在搜索的时候,搜索结果出来后对你输入的关键字进行红色标记。这样用户就很请楚的看到自己输入什么后会出现什么样子的结果。还有一个功能是,现在有一段文字了,但是要对其中的某些字符串进行着色处理,这个时候NSAttibutedString起到了非常大的作用。以下是我写好的一段代码,各位可以拿去用,非常方便的处理好。

#import <Foundation/Foundation.h>

@interface NSAttributedString (Color)
/**
 *  对内容中部份关键字进行着色处理
 *
 *  @param content 所有内容
 *  @param searchs 关键字数组
 *
 *  @return
 */
+(NSAttributedString *)attributeStringWithContent:(NSString *)content keyWords:(NSArray *)keyWords;
@end

 

#import "NSAttributedString+Color.h"

@implementation NSAttributedString (Color)

+(NSAttributedString *)attributeStringWithContent:(NSString *)content keyWords:(NSArray *)keyWords
{
    UIColor *color=[UIColor redColor];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:content];
    if (keyWords) {
        [keyWords enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSRange range=[content rangeOfString:obj];
            NSInteger location=0;
            while (range.length>0) {
                [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:color range:NSMakeRange(location+range.location, range.length)];
                location+=(range.location+range.length);
                NSString *tmp= [content substringWithRange:NSMakeRange(range.location+range.length, content.length-location)];
                range=[tmp rangeOfString:obj];
            }
            
        }];
    }
    
    return attString;
}
@end

  之前也有看到类似的第三方,他是指写位置,哪个位置到哪个位置的,这里的话是直接指定字符串,而且,出现多次的,一样可以全部着色。大家可以根据自身需求进行细微的调整。

   2,还有一种情况,当后台返回的内容中带有html独有的标签怎么办?当然,你可以选择一些第三方来处理,但是对比你想要的功能后,可以发现,这并不是你想要的,太笨重了,我只是要把html标签去了,或是就按html里面的格式显示 。但是又不想用webview去显示 ,因 为webview不能对这些文本进行编辑。这里我就简单写个把html转成NSAttibutedString的方法。

 

+(NSAttributedString *)attributedStringWithHtml:(NSString *)html
{
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSMutableAttributedString *attrString=[[NSMutableAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES] options:options documentAttributes:nil error:nil];
    return attrString;
    
}

   这里返回的是按照原来的html格式,CSS样式一样生效的。如果你只想把html标签去了,而不要显示成有CSS样式的,你可以直接在返回的attrString中再调用[attrString string]方法就可以,然后直接显示在label或者textView在,非常的方便。

  感觉大家阅读。

iOS中NSAttributedString的使用--对关键字着色,以及处理html实例

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!