1树瞭、首先獲取本地通訊錄
2、根據(jù)姓名和手機號實現(xiàn)搜索功能,當然拼音搜索也是支持的
1.1、今天在實現(xiàn)項目功能上需要獲取本地的通訊錄,然后在去自定義tableview顯示通訊錄信息寄啼,再然后就是實現(xiàn)搜索功能,在網(wǎng)上找了一圈都沒合適的就自己動手開始寫了赘淮。
1.2辕录、獲取到手機的通訊錄相信大家都知道怎么搞睦霎,我這里是直接使用的前輩封裝好的PPGetAddressBook再次感謝這些開源作者
1.3梢卸、額,逼逼兩分鐘讓大家看看效果圖吧
2.1副女、下面咱們還是直接看代碼吧
創(chuàng)建tableview的搜索頭蛤高。
_headView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH, 54)];
_headView.backgroundColor = [UIColor whiteColor];
_searchBar = [[UISearchBar alloc] init];
_searchBar.placeholder = @"搜索聯(lián)系人";
_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、實現(xiàn)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];//講搜索后的數(shù)據(jù)添加到數(shù)組中
}else{
if (isPY && !isHas) {
//迷糊查找
LLAppLog(@"----%@",model.name);
[self.searchArr addObject:model];
}
}
}
[self.tableView reloadData];
}
結(jié)尾
寫的不好戴陡,或者有問題的地方歡迎大家評論指出呀。沟涨。小弟是彩筆
雖然不夠好恤批,但是demo還是有的(https://github.com/HeQianLong/AddressSearch/tree/master)