iOSがiPhoneカメラとアルバムを開く


一.エージェントの追加
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;"><UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate></span>

二.画像を表示するボタンを追加
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;">- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 80, 80);
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)addImage
{
    UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@" " delegate:self cancelButtonTitle:@" " destructiveButtonTitle:nil otherButtonTitles:@" ",@" ",nil];
    [sheet showInView:self.view];
}</span>

三.UIActionSheetDelegate、対応するカメラとアルバムを開く
#pragma mark -- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            // 
            // 
            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(@" ");
            }
        }
            
            break;
        case 1:
        {
            // 
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            // 
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            // 
            picker.allowsEditing = YES;
            //    [self presentModalViewController:picker animated:YES];
            [self presentViewController:picker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

四.画像セレクタの依頼方法、画像を選択した後にこの方法をコールバックします
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;">#pragma Delegate method UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    
    // 
    if (image != nil) {
        // 
        [button setBackgroundImage:image forState:UIControlStateNormal];
    }
    // 
    [picker dismissModalViewControllerAnimated:YES];
}</span>