iOS图片选取器

首先,在.h页面添加相关协议

<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];

    

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值