// 需要导入 AddressBookUI.framework,AddressBook.framework 框架
// ViewController.h
#import <UIKit/UIKit.h>
#import <AddressBookUI/AddressBookUI.h>
@interface ViewController : UIViewController
<ABPeoplePickerNavigationControllerDelegate>
@property (nonatomic,retain) UITextField *personField;
@end
//ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize personField;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
personField = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 200, 30)];
personField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:personField];
[personField release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(220, 50, 90, 30);
[button setTitle:@"选择联系人" forState:UIControlStateNormal];
[button addTarget:self action:@selector(selectPerson:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)selectPerson:(id)sender
{
//创建选择联系人的导航控制器
ABPeoplePickerNavigationController *peoplePickerController = [[ABPeoplePickerNavigationController alloc] init];
//设置回调
peoplePickerController.peoplePickerDelegate = self;
//显示通讯录
[self presentModalViewController:peoplePickerController animated:YES];
}
//回调方法,当用户在通讯录上选择取消时调用
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
//关闭通讯录
[self dismissModalViewControllerAnimated:YES];
}
//回调方法,当用户在通讯录上选择一个联系人时调用
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
//姓名
NSString *name = (__bridge NSString *)ABRecordCopyCompositeName(person);
//在输入框上显示
personField.text = name;
//关闭通讯录
[self dismissModalViewControllerAnimated:YES];
return NO;
}
//回调方法,当用户选择某个联系人的某个属性时调用
//iPhone有一些缺省操作,比如:当你选择某个电话时,就直接打过去.为了不触发这些操作,返回NO
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return NO;
}