- (IBAction)touchSelectImg:(id)sender { //在這裏呼出下方菜單按鈕項 UIActionSheet *myActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles: @"打開照相機", @"從手機相冊獲取",nil]; [myActionSheet showInView:self.view]; }
<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>spa
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { //呼出的菜單按鈕點擊後的響應 if (buttonIndex == actionSheet.cancelButtonIndex){ NSLog(@"取消"); }else{ switch (buttonIndex){ case 0: //打開照相機拍照 [self takePhoto]; break; case 1: //打開本地相冊 [self LocalPhoto]; break; } } } //開始拍照 -(void)takePhoto { UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; //設置拍照後的圖片可被編輯 picker.allowsEditing = YES; picker.sourceType = sourceType; [self presentViewController:picker animated:YES completion:nil]; }else { NSLog(@"模擬其中沒法打開照相機,請在真機中使用"); } } //打開本地相冊 -(void)LocalPhoto { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; picker.delegate = self; //設置選擇後的圖片可被編輯 picker.allowsEditing = YES; [self presentViewController:picker animated:YES completion:nil]; } //當選擇一張圖片後進入這裏 -(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *type = [info objectForKey:UIImagePickerControllerMediaType]; //當選擇的類型是圖片 if ([type isEqualToString:@"public.image"]) { UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; [picker dismissViewControllerAnimated:YES completion:nil]; } } //您取消了選擇圖片 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { NSLog(@"您取消了選擇圖片"); [picker dismissViewControllerAnimated:YES completion:nil]; }