标签:
IOS - 模糊搜索
这里模糊搜索 不是在数据中的,而是在数组,或者你需要的地方
首先先看一下效果:
所搜之前:
搜索之后:
下面思路讲解:
1.定义好需要加载数据的数组
这里需定义一个模型,加载数组中的内容,在模型中在加入两个变量,一个是拼音,一个是拼音的首字母
2. 在数组加载到模型中的时候,将数组中的一对象 获取到 拼音,和拼音的首字母
// pinyin
- (NSString *)transformToPinyin{
NSMutableString * mutableString = [NSMutableString stringWithString:self];
CFStringTransform((CFMutableStringRef) mutableString, NULL, kCFStringTransformToLatin, false);
mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
mutableString = [[mutableString stringByReplacingOccurrencesOfString:@" " withString:@""] mutableCopy];
return mutableString.lowercaseString;
}
//
- (NSString * )transformToPinyinFirstLetter{
NSMutableString * stringM = [NSMutableString string];
NSString * temp = nil;
for (int i = 0; i < [self length]; i ++) {
temp = [self substringWithRange:NSMakeRange(i, 1)];
NSMutableString * mutableString = [NSMutableString stringWithString:temp];
CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
mutableString = [[mutableString substringToIndex:1] mutableCopy];
[stringM appendString:(NSString *)mutableString];
}
return stringM.lowercaseString;
}
将这两个方法添加到NSString的分类中,作用是:获取一个字符串对像的拼音,和拼音首字母
+ (NSString *)getPinyinWithString:(NSString *)string{
NSString * pinyin;
if ([string length]) {
NSMutableString * ms = [[NSMutableString alloc] initWithString:string];
if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
}
if (CFStringTransform( (__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
}
pinyin = ms;
}
return pinyin;
}
+ (NSString *)getFirstLetterWithString:(NSString *)string{
NSString * regex = @"^[a-zA-Z]*$";
NSString * firstLetter = [string substringToIndex:1];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([predicate evaluateWithObject:firstLetter] == YES) {
return [firstLetter uppercaseString];
}else {
return @"~";
}
}
将汉字转换成拼音
做好了这些以后,所有就是把你所搜的内容在 模型数组中搜索,所搜到的时候就显示出来
代码在GitHub上面有需要可以下载看看:https://github.com/Amuxiaomu/SearchDemo
标签:
原文地址:http://www.cnblogs.com/DreamLinku/p/5743296.html