<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
然后,创建UIImagePickerController实例
@property(strong,nonatomic)UIImagePickerController *imagePicker;
并对其进行配置
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;
self.imagePicker.allowsEditing = YES;//允许照片编辑
添加UIButton控件
@property (weak, nonatomic) IBOutlet UIButton *image;
为button添加一个事件
- (IBAction)selectImage:(UIButton *)sender {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//判断是否支持相机
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action){
//设置数据源类型
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
[alert addAction:cameraAction];
}
UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action){
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
[alert addAction:photoAction];
UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"最近照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action){
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
[alert addAction:albumAction];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
[self.image setImage:image forState:UIControlStateNormal];
}