1、首先获取本地通讯录
2、根据姓名和手机号实现搜索功能,当然拼音搜索也是支持的
1.1、今天在实现项目功能上需要获取本地的通讯录,然后在去自定义tableview显示通讯录信息,再然后就是实现搜索功能,在网上找了一圈都没合适的就自己动手开始写了。
1.2、获取到手机的通讯录相信大家都知道怎么搞,我这里是直接使用的前辈封装好的PPGetAddressBook再次感谢这些开源作者
1.3、额,逼逼两分钟让大家看看效果图吧
2.1、下面咱们还是直接看代码吧
创建tableview的搜索头。
_headView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH, 54)];
_headView.backgroundColor = [UIColor whiteColor];
_searchBar = [[UISearchBar alloc] init];
_searchBar.placeholder = @"搜索联系人";
_searchBar.delegate = self;
_searchBar.frame = CGRectMake(15,7,SCREEN_WIDTH - 30,40);
_searchBar.backgroundColor = BackGroundColcor;
_searchBar.backgroundImage = [UIImage new];
_searchBar.layer.cornerRadius = 3;
_searchBar.layer.masksToBounds = YES;
[_searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];
[_headView addSubview:self.searchBar];
2.2、实现UISearchBar的代理方法
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if (searchText.length > 0) {
self.isSearch = YES;
}else{
self.isSearch = NO;
[searchBar resignFirstResponder];
}
[self.searchArr removeAllObjects];
for (int i = 0; i<self.allPeopleArr.count; i++) {
PPPersonModel *model = self.allPeopleArr[i];
NSString *lowStr = [ChineseToPinyin pinyinFromChineseString:searchText withSpace:NO ];
NSString *allStr =[ChineseToPinyin pinyinFromChineseString:model.name withSpace:NO ];
//**********手机号模糊搜索*************//
if (model.mobileArray.count == 1) {
if ([model.mobileArray[0] rangeOfString:searchText].location != NSNotFound) {
[self.searchArr addObject:model];
}
}else{
for (int i= 0; i<model.mobileArray.count; i++) {
if ([model.mobileArray[i] rangeOfString:searchText].location != NSNotFound) {
[self.searchArr addObject:model];
}
}
}
//**********姓模糊搜索*************//
self.searchKeyText = [NSString stringWithFormat:@"%c",[ChineseToPinyin sortSectionTitle:searchText]];
BOOL isHas = [allStr isEqualToString:lowStr];
BOOL isPY = false;
if ( lowStr || lowStr.length != 0) {
isPY = [allStr hasPrefix:lowStr];
}
if (isHas) {
//这种情况是精确查找。
LLAppLog(@"%@",model.name);
[self.searchArr addObject:model];//讲搜索后的数据添加到数组中
}else{
if (isPY && !isHas) {
//迷糊查找
LLAppLog(@"----%@",model.name);
[self.searchArr addObject:model];
}
}
}
[self.tableView reloadData];
}
结尾
写的不好,或者有问题的地方欢迎大家评论指出呀。。小弟是彩笔
虽然不够好,但是demo还是有的(https://github.com/HeQianLong/AddressSearch/tree/master)