之前学过这个,没写博客。有点忘了,再写一次
开启权限
在info文件里开启权限
代码
// ViewController.h
// 手机相册
//
// Created by 王璐 on 2023/4/11.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController* imagePicker;
@property (nonatomic, strong) UIButton* button;
@end
// ViewController.m
// 手机相册
//
// Created by 王璐 on 2023/4/11.
//
#import "ViewController.h"
#import "AVFoundation/AVFoundation.h"
#import "AssetsLibrary/AssetsLibrary.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.button = [UIButton buttonWithType:UIButtonTypeClose];
[self.button setImage:[UIImage imageNamed:@"touxiang.png"] forState:UIControlStateNormal];
self.button.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:self.button];
[self.button addTarget:self action:@selector(press) forControlEvents:UIControlEventTouchUpInside];
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.editing = YES;
self.imagePicker.delegate = self;
self.imagePicker.allowsEditing = YES;
self.imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
// Do any additional setup after loading the view.
}
- (void)press {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择照片来源" message:@"" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
UIAlertAction *photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:camera];
[alert addAction:photo];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}
@end