
正文
iOS从手机相册选择一张照片并显示 Objective-C
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
要先给app设置访问相册的权限:
在项目的Info.plist文件里添加Privacy - Photo Library Usage Description权限
ViewController.h:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController
{
IBOutlet UIImageView *myImageView; //与ImageView视图关联
} - (IBAction)buttonUp:(id)sender; // 与一个Button关联 @end
ViewController.m:
#import "ViewController.h" @interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>//接口 @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (IBAction)buttonUp:(id)sender {
//初始化UIImagePickerController类
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
//判断数据来源为相册
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//设置代理
picker.delegate = self;
//打开相册
[self presentViewController:picker animated:YES completion:nil];
} //选择完成回调函数
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//获取图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:nil]; myImageView.image = image;
} //用户取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[self dismissViewControllerAnimated:YES completion:nil];
} @end





