iOS索引列開發,這有篇文章
http://www.cocoachina.com/ios/20140919/9692.html
下面是我自己的:
#import "ContactsModel.h"
#import "XDSearchBar.h"
這兩個是我自定義的類,一個聯繫人model ,一個搜索欄,
#import <UIKit/UIKit.h>
#import "ContactsModel.h"
#import "XDSearchBar.h"
@interface AddressBookViewController : KViewController<UITableViewDataSource,UITableViewDelegate>
{
XDSearchBar *mySearchBar;
UITableView *listTableView;
NSMutableArray *contactsArray;
NSMutableArray *showDataArray;
}
@property(nonatomic, strong) void(^didSelectContactBlock)(BOOL isSelect,ContactsModel *contact);
@end
#import "AddressBookViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
@interface AddressBookViewController ()
@end
@implementation AddressBookViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"聯繫人";
#pragma mark--搜索視圖
mySearchBar = [[XDSearchBar alloc] init];
mySearchBar.frame = CGRectMake(0, 0, listTableView.width, 35);
mySearchBar.placeholder = @"輸入關鍵字進行收索";
__weak __typeof(self)weakSelf = self;
mySearchBar.searchBarBlock = ^(XDSearchBarStatus status,NSString *key){
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (status == XDSearchBar_TapSearchButton) {
[strongSelf searchDataBySearchKey:key];
}
else if (status == XDSearchBar_TapCancel){
[strongSelf searchDataBySearchKey:nil];
}
else{}
};
//列表
listTableView = [StaticFun creatTableViewWithTarget:self];
listTableView.frame = CGRectMake(0, 64, boundsWidth, boundsHeight - 64);
[self.view addSubview:listTableView];
listTableView.tableHeaderView = mySearchBar;
NSLog(@"status:%ld",ABAddressBookGetAuthorizationStatus());
if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {
[self alertMessage];
}
else{
showDataArray = [NSMutableArray arrayWithCapacity:10];
contactsArray = [[NSMutableArray alloc] init];
[self readABAddressBook:^(bool compelete, NSMutableArray *peopleArray) {
dispatch_async(dispatch_get_main_queue(), ^{
if (compelete) {
contactsArray = [self SelectFromBook:peopleArray];
showDataArray = [contactsArray mutableCopy];
[listTableView reloadData];
}
else{
[listTableView reloadData];
}
});
}];
}
}
#pragma mark--
#pragma mark--搜索
-(void)searchDataBySearchKey:(NSString *)searchKey{
if (searchKey) {
[showDataArray removeAllObjects];
for (int i = 0; i < [contactsArray count]; i++) {
ContactsModel *model = (ContactsModel *)[contactsArray objectAtIndex:i];
NSString *name = model.name;
if([name rangeOfString:searchKey].location != NSNotFound){
[showDataArray addObject:model];
}
else{
}
}
[listTableView reloadData];
}
else{
showDataArray = [contactsArray mutableCopy];
[listTableView reloadData];
}
}
#pragma mark--
#pragma mark--UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [showDataArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[showDataArray objectAtIndex:section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (showDataArray.count > indexPath.section) {
NSArray *dataArray = [showDataArray objectAtIndex:indexPath.section];
if (dataArray.count > indexPath.row) {
ContactsModel *model = (ContactsModel *)[dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = model.name;
cell.detailTextLabel.text = model.phone;
}
}
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *title = [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
return [NSString stringWithFormat:@" %@",title];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return [[showDataArray objectAtIndex:section] count] ? 25 : 0;;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:
[[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}
#pragma mark--
#pragma mark--UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.didSelectContactBlock) {
NSArray *dataArray = [showDataArray objectAtIndex:indexPath.section];
ContactsModel *model = (ContactsModel *)[dataArray objectAtIndex:indexPath.row];
self.didSelectContactBlock(YES,model);
[self.navigationController popViewControllerAnimated:YES];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)showHUD
{
[SVProgressHUD showWithStatus:@"正在加載通訊錄..." maskType:SVProgressHUDMaskTypeBlack];
}
-(void)alertMessage{
UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"提示" message:@"用戶已禁止授權訪問通訊錄,請到 設置->隱私->通訊錄 中更改設置" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alrt show];
}
-(NSMutableArray *)SelectFromBook:(NSMutableArray *)formBookArray
{
//列表索引 和字母排序
NSMutableArray *titleArray = [[NSMutableArray alloc] init];
self.searchDisplayController.searchResultsTableView.scrollEnabled = YES;
self.searchDisplayController.searchBar.showsCancelButton = NO;
UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];
for (ContactsModel *addressBook in formBookArray) {
NSInteger sect = [theCollation sectionForObject:addressBook
collationStringSelector:@selector(name)];
addressBook.sectionNumber = sect;
}
NSInteger highSection = [[theCollation sectionTitles] count];
NSMutableArray *sectionArrays = [NSMutableArray arrayWithCapacity:highSection];
for (int i=0; i <= highSection; i++) {
NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
[sectionArrays addObject:sectionArray];
}
for (ContactsModel *addressBook in formBookArray) {
[(NSMutableArray *)[sectionArrays objectAtIndex:addressBook.sectionNumber] addObject:addressBook];
}
for (NSMutableArray *sectionArray in sectionArrays) {
NSArray *sortedSection = [theCollation sortedArrayFromArray:sectionArray collationStringSelector:@selector(name)];
[titleArray addObject:sortedSection];
}
return titleArray;
}
#pragma mark--讀取所有聯繫人
-(void)readABAddressBook:(void(^)(bool compelete,NSMutableArray *peopleArray))block {
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = nil;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
{
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookRequestAccessWithCompletion != NULL) {
//等待同意後向下執行
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//dispatch_release(sema);
}
}
else
{
addressBook = ABAddressBookCreate();
}
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!granted) {
[SVProgressHUD dismiss];
// Do whatever you want here.
[self alertMessage];
return;
}
});
});
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;peopleCounter < [arrayOfAllPeople count]; peopleCounter++)
{
NSMutableDictionary *localPeopleDic = [[NSMutableDictionary alloc] init];
ABRecordRef thisPerson = (__bridge ABRecordRef) [arrayOfAllPeople objectAtIndex:peopleCounter];
//名字
NSString *name = (__bridge_transfer NSString *) ABRecordCopyCompositeName(thisPerson);
NSLog(@"name:%@",name);
if (!name) {
name = @" ";
}
[localPeopleDic setObject:name forKey:@"name"];
//電話
ABMultiValueRef phones = ABRecordCopyValue(thisPerson, kABPersonPhoneProperty);
for (NSUInteger phoneCounter = 0; phoneCounter < ABMultiValueGetCount(phones); phoneCounter++)
{
NSString *phoneNumber = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, phoneCounter);
phoneNumber = [self trimSting:phoneNumber];
NSLog(@"phone : %@",phoneNumber);
[localPeopleDic setObject:phoneNumber forKey:@"phone"];
}
ContactsModel *model = [[ContactsModel alloc] initWithDictionary:localPeopleDic];
[tempArray addObject:model];
}
CFRelease(addressBook);
if (tempArray.count > 0) {
block(YES,tempArray);
}
else{
block(NO,nil);
}
}
#pragma mark 去掉不要的字符(比如:-、()等等)
- (NSString *)trimSting:(NSString *)str
{
str = [str stringByReplacingOccurrencesOfString:@"(" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"-" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
return str;
}
@end