iOS之相册实现
代码演示:
- (IBAction)btAction:(UIButton *)sender { //创建提示框 控制器 UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示框" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; //创建相机的点击事件按钮 UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){ //判断系统设备是否存在相机,有调用 没有提醒用户 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { //如果有摄像头 ,创建相机 UIImagePickerController *picker = [[ UIImagePickerController alloc] init]; //指定数据来源,来自于相机 picker.sourceType = UIImagePickerControllerSourceTypeCamera; picker.delegate = self; picker.allowsEditing = YES;//允许编辑 //使用模态弹出相机 [self presentViewController:picker animated:YES completion:nil]; }else { //没有摄像头提醒用户,您的设备没有摄像头 UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"您的设备没有摄像头" message:nil preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]; [controller addAction:action]; [self presentViewController:controller animated:YES completion:nil]; } }]; [alertC addAction:alertA];//添加到提示框 //创建相册的点击事件按钮, UIAlertAction *action = [ UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){ UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//指定数据来源是相册 picker.delegate = self; picker.allowsEditing = YES; [self presentViewController:picker animated:YES completion:nil]; }]; [alertC addAction:action]; [self presentViewController:alertC animated:YES completion:nil]; } //选取图片之后执行的方法 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ NSLog(@"%@",info);//是个字典 //通过字典的key值来找到图片 UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];//并且赋值给声明好的imageView self.imageView.image = image; //最后模态返回 最初的 控制器 [picker dismissViewControllerAnimated:YES completion:nil]; }