#import "ViewController.h"
@interface ViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建显示照片的imageView
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 200, 200)];
[self.view addSubview:self.imageView];
// 创建选择照片按钮
UIButton *choosePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
[choosePhotoButton setTitle:@"选择照片" forState:UIControlStateNormal];
choosePhotoButton.frame = CGRectMake(50, 350, 100, 50);
[choosePhotoButton addTarget:self action:@selector(choosePhoto) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:choosePhotoButton];
}
- (void)choosePhoto {
// 检查相册是否可用
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"相册不可用" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
return;
}
// 创建 UIImagePickerController
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];
}
// 选择照片完成后调用的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
self.imageView.image = selectedImage;
[picker dismissViewControllerAnimated:YES completion:nil];
}
// 用户取消选择照片时调用的代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
@end
ios实现选择照片并显示在界面上
最新推荐文章于 2024-05-17 18:08:44 发布