签两个代理
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
创建UIImagePickerController对象
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = YES;
picker.delegate = self;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:NO completion:^{}];
}];
[alert addAction:action1];
}
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"相机" style:0 handler:^(UIAlertAction *action) {
}];
[alert addAction:action2];
}
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从图片库获取" style:0 handler:^(UIAlertAction *action) {
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:picker animated:NO completion:^{}];
}];
[alert addAction:action3];
}
设置取消按键推出界面
UIAlertAction *cancel =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
}];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:^{
}];
调用协议方法选取照片使用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = info[@"UIImagePickerControllerEditedImage"]; /**< 字典中获取对象的字面量写法 */
[self.addC.button setBackgroundImage:image forState:UIControlStateNormal];
[picker dismissViewControllerAnimated:YES completion:^{}];
}