1 2 3 1. 4 5 UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle: @"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"选择本地图片",@"拍照", nil]; 6 7 [actionSheet showInView:self.view]; 8 9 10 11 //2.实现相应代理事件,代理UIActionSheetDelegate,方法如下 12 13 14 15 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex { 16 17 // 相册 0 拍照 1 18 19 switch (buttonIndex) { 20 21 case 0: 22 23 //从相册中读取 24 25 [self readImageFromAlbum]; 26 27 break; 28 29 case 1: 30 31 //拍照 32 33 [self readImageFromCamera]; 34 35 break; 36 37 default: 38 39 break; 40 41 } 42 43 } 44 45 46 47 //3.实现从相册读取图片功能,代码如下 48 49 50 51 52 53 //从相册中读取 54 55 - (void)readImageFromAlbum { 56 57 //创建对象 58 59 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; 60 61 //(选择类型)表示仅仅从相册中选取照片 62 63 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 64 65 //指定代理,因此我们要实现UIImagePickerControllerDelegate, UINavigationControllerDelegate协议 66 67 imagePicker.delegate = self; 68 69 //设置在相册选完照片后,是否跳到编辑模式进行图片剪裁。(允许用户编辑) 70 71 imagePicker.allowsEditing = YES; 72 73 //显示相册 74 75 [self presentViewController:imagePicker animated:YES completion:nil]; 76 77 } 78 79 80 81 //4.实现拍照功能 82 83 84 85 - (void)readImageFromCamera { 86 87 if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { 88 89 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; imagePicker.delegate = self; 90 91 imagePicker.allowsEditing = YES; 92 93 //允许用户编辑 94 95 [self presentViewController:imagePicker animated:YES completion:nil]; 96 97 } else { 98 99 //弹出窗口响应点击事件 100 101 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"未检测到摄像头" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil]; 102 103 [alert show]; 104 105 } 106 107 } 108 109 110 111 //5.图片完成处理后提交,代理方法UIPickerControllerDelegate 112 113 114 115 //图片完成之后处理 116 117 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { 118 119 //image 就是修改后的照片 120 121 //将图片添加到对应的视图上 122 123 [_headImageView setImage:image]; 124 125 //结束操作 126 127 [self dismissViewControllerAnimated:YES completion:nil]; 128 129 } 130 131