今天主要是做项目,所有没有花多少时间学习新知识。主要看了下访问相册的功能。
新建一个项目,然后在项目里新建一个视图控制器MainViewController。在控制器视图中添加一个图片视图和一个按钮。当按下按钮时,会执行chooseImage方法。
-(void)loadView{
UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
self.view = view;
//创建图片视图
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 200, 400, 300)];
[view addSubview:self.imageView];
//创建按钮
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
button.backgroundColor = [UIColor yellowColor];
[button setTitle:@"选择图片" forState:UIControlStateNormal];
//添加事件
[button addTarget:self action:@selector(chooseImage) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
}
在chooseImage方法中,我们创建UIImagePickerController对象。UIImagePickerController可以用于访问相册。想要获得选中的图片,必须实UIImagePickerControllerDelegate协议。然后在imagePickerController:didFinishPickingImage:editingInfo:方法中获得被选中图片,并进行相应操作。
//访问相册,选择图片
-(void)chooseImage{
//创建ImagePicker
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//设置代理
imagePicker.delegate = self;
//设置数据类型
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagePicker.allowsEditing = YES;
//显示
[self presentModalViewController:imagePicker animated:YES];
}
我们在代理方法中,将获得的图片设为imageView的图片。
//代理方法,获得图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
//设置图片
self.imageView.image = image;
[self dismissModalViewControllerAnimated:YES];
}
最后在应用程序的代理类中创建视图控制器,并运行。
//创建控制器
MainViewController *vc = [[MainViewController alloc] init];
self.window.rootViewController = vc;
运行结果截图: