在iPhone中获取照片库的常用方法如下:
- UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
- if ([UIImagePickerController isSourceTypeAvailable:
- UIImagePickerControllerSourceTypePhotoLibrary]) {
- imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- imagePicker.delegate = self;
- [imagePicker setAllowsEditing:NO];
- [self presentModalViewController:imagePicker animated:YES];
- [imagePicker release];
- } else {
- UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Error accessing photo library!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
- [alert show];
- [alert release];
- }
这在iPhone下操作是没有问题的,但在iPad下就会有问题了,运行时会报出下面的错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'On iPad, UIImagePickerController must be presented via UIPopoverController'
所以,我们必须通过UIPopoverController来实现才行。具体的实现如下:
- UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
- if ([UIImagePickerController isSourceTypeAvailable:
- UIImagePickerControllerSourceTypePhotoLibrary]) {
- imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- imagePicker.delegate = self;
- [imagePicker setAllowsEditing:NO];
- UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
- self.popoverController = popover;
- [popoverController presentPopoverFromRect:CGRectMake(0, 0, 300, 300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
- [popover release];
- [imagePicker release];
- } else {
- UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Error accessing photo library!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
- [alert show];
- [alert release];
- }
转自:http://2015.iteye.com/blog/1340797