iOS如何启动图像选择器

时间:2014-06-07 15:45:06

标签: ios objective-c uiimagepickercontroller

我有一个UIButton,当用户点击它时,我想启动图像选择器控制器

我已经配置了我认为已经足够但我无法知道我必须传递给该图像选择器才能开始工作的消息

这是我的代码

#import "ImagePickerViewController.h"

@interface ImagePickerViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *image;


@end

@implementation ImagePickerViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (IBAction)SelectImage:(id)sender {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}

@end

我已经设置了正确的协议:

@interface ImagePickerViewController : UIViewController < UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容显示选择器:

[self presentViewController:imagePicker animated:YES completion:NULL];

然后在您的委托回调imagePickerController:didFinishPickingMediaWithInfo中,您获得了图片并再次关闭了选择器:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
      UIImage *image = info[UIImagePickerControllerEditedImage]; 
      [picker dismissViewControllerAnimated:YES completion:NULL];  

}

答案 1 :(得分:0)

您需要提供UIImagePicker

- (IBAction)SelectImage:(id)sender
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePicker animated:NO completion:nil];
}

答案 2 :(得分:0)

您必须告诉视图控制器类显示UIImagePickerController。

只需使用

[self presentViewController:imagePicker animated:YES completion:nil];

这将以模态方式呈现。如果您在iPad上运行,则必须将其显示在弹出控制器中,如下所示:

在@interface中声明一个新属性:

@property (nonatomic, strong) UIPopoverController* imagePickerPopover;  

呈现弹出控制器,例如:

UIButton* button = sender;
self.imagePickerPopover = [[UIPopoverController alloc] initWithContentViewController:self.imagePicker];
[self.imagePickerPopover presentPopoverFromRect:button.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];