我的 View Controller 上有 3 个 ImageView 。我可以选择从图库中选择或拍照。现在,我想要的是相机。我想默认选择图像,我们可以选择一张,但我想要三张,如何实现。
最佳答案
使用Tag
概念`
第 1 步
最初为每个 imageView 分配标签为 1,2,3
并具体介绍打开 UIImagePickerController
的一种常用方法
第 2 步
为每个图像创建手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
tap.cancelsTouchesInView = YES;
tap.numberOfTapsRequired = 1;
tap.delegate = self;
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:tap];
调用方法如
- (IBAction)handleImageTap:(UIGestureRecognizer*)sender
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Attach image" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* pickFromGallery = [UIAlertAction actionWithTitle:@"Take a photo"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController* picker = [[UIImagePickerController alloc] init];
picker.view.tag = sender.view.tag;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:NULL];
}
}];
UIAlertAction* takeAPicture = [UIAlertAction actionWithTitle:@"Choose from gallery"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
UIImagePickerController* picker = [[UIImagePickerController alloc] init];
picker.view.tag = sender.view.tag;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:NULL];
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {
}];
[alertController addAction:pickFromGallery];
[alertController addAction:takeAPicture];
[alertController addAction:cancel];
[self presentViewController:alertController animated:YES completion:NULL];
}
第 3 步
在该委托(delegate)方法上
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
if(picker.view.tag == 1)
{
// assign the image to first
}
else if(picker.view.tag == 2)
{
// assign the image to second
}
else
{
// assign the image to third
}
}
关于ios - 来自相机的多个 imagePicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38606356/