Tuesday, December 15, 2015

Image Picker View Example in iOS

//In .h File...

IBOutlet UIImageView *userPic;



//In .m File...

#pragma mark - Button Action Methods

- (IBAction)chooseProofilePic:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet allocinitWithTitle:@"Choose your photo"delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nilotherButtonTitles:@"Choose from library"@"Use camera"nil];
    [actionSheet showInView:self.view];
}


#pragma mark - Actionsheet delegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    NSLog(@"%ld",(long)buttonIndex);
    
    if (buttonIndex==1) {
        //Take Picture
        
        imagePicker = [[UIImagePickerController allocinit];
        // Set source to the camera
        
    #if (TARGET_IPHONE_SIMULATOR)
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
    #else
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        
    #endif
        // Delegate is self
        imagePicker.delegate = self;
        
        // Allow editing of image ?
        [imagePicker setAllowsEditing:YES];
        // Show image picker
        [self presentViewController:imagePicker animated:NO completion:nil];
        // [self presentModalViewController:imagePicker animated:YES];
    }
    else if(buttonIndex==0){
        //Choose From Library
        imagePicker = [[UIImagePickerController allocinit];
        
        // Set source to the camera
        imagePicker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        
        // Delegate is self
        imagePicker.delegate = self;
        
        // Allow editing of image ?
        [imagePicker setAllowsEditing:YES];
        // Show image picker
        [self presentViewController:imagePicker animated:NO completion:nil];
        //[self presentModalViewController:imagePicker animated:YES];
    }
    else{
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
        //cancel
    }
}



#pragma mark Image Picker delegate

- (void)imagePickerController:(UIImagePickerController *)picker1 didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    
    [picker1 dismissViewControllerAnimated:YES completion:^{
        userPic.image = chosenImage;
    }];
}

No comments:

Post a Comment