效果
有一个头像按钮,点击进入相册,从相册中获取图片,更改按钮的图片为选取的图片
- 创建一个自定义UIButton按钮,并给一张图片
- (void)createButton {
//获取一张图片
UIImage *image = [UIImage imageNamed:@"image.jpg"];`
//给button一张图片
[self.button setImage:image forState:UIControlStateNormal];
self.button.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:self.button];
//设置button的点击事件
[self.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];`
}
- button的点击事件
- (void)buttonAction:(UIButton *)button{
//创建一个 UIImagePickerController对象
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//是否允许用户编辑
picker.allowsEditing = YES;
//指定数据源
//数据源是枚举值 一共有三种
//UIImagePickerControllerSourceTypePhotoLibrary 从图库获取(所有图片)
//UIImagePickerControllerSourceTypeCamera 使用相机拍摄获取
//UIImagePickerControllerSourceTypeSavedPhotosAlbum 从相册获取(仅是相机拍摄的所有图片)
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//指定代理人为self
//设置代理人之前要签订两个协议
picker.delegate = self;
//模态推入相册控制器
[self presentViewController:picker animated:YES completion:^{
}];
}
- 签订协议
//两个协议配套使用,缺一不可
@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@end
- 实现相册协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
// 打印方法的形参info->观察结果是一个"字典"
// NSLog(@"%@", info);
// 通过字典里面的UIImagePickerControllerOriginalImage找到获取的相册图片
UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
// 将获取的图片设置为头像
[self.button setImage:image forState:UIControlStateNormal];
// 收回相册控制器
[self dismissViewControllerAnimated:YES completion:^{
}];
}