项目中用到,自己就封起来了,话不多说上代码。
首先懒加载,相册按钮,以及设置方法
- (UIButton*)Camera {
if (!_Camera) {
_Camera = [UIButton new];
[_Camera setImage:[UIImage imageNamed:@"xiangji"]
forState:(UIControlStateNormal)];
// 控制照相机功能
[_Camera addTarget:self action:@selector(pressAc:) forControlEvents:UIControlEventTouchUpInside];
}
return _Camera;
}
其次直接调用方法,书写
- (void)pressAc:(UIButton *)sender {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//按钮:从相册选择,类型:UIAlertActionStyleDefault
[alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//初始化UIImagePickerController
UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//允许编辑,即放大裁剪
PickerImage.allowsEditing = YES;
//自代理
PickerImage.delegate = self;
//页面跳转
[self presentViewController:PickerImage animated:YES completion:nil];
}]];
//按钮:拍照,类型:UIAlertActionStyleDefault
[alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
//获取方式:通过相机
PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
PickerImage.allowsEditing = YES;
PickerImage.delegate = self;
[self presentViewController:PickerImage animated:YES completion:nil];
}]];
//按钮:取消,类型:UIAlertActionStyleCancel
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}
// PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//定义一个image,用来存放我们选择的图片,转化为NSData
UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
// self.patientImgV.image = image;
//[self.uploadPicBtn setImage:image forState:UIControlStateNormal];
[self dismissViewControllerAnimated:YES completion:nil];
// 好像要调用修改头像接口,将头像上传到服务器
}
看不懂的小伙伴,直接复制粘贴,复制粘贴,复制粘贴,重要的事情说三遍,
联系QQ:365728030.