将拍摄的图像分配给ImageView

时间:2015-09-22 05:15:07

标签: ios objective-c

我有两个视图控制器。 ViewControllerAViewcontrollerBViewControllerA有一个按钮,可以让您ViewControllerB通过segue。

ViewControllerB允许用户通过设备相机拍摄照片,并应在ViewcontrollerA中分配此图像。但是我的应用程序崩溃了。

ViewControllerA

@property (strong, nonatomic) IBOutlet UIImageView *userPicture;

ViewControllerB

- (void)imagePickerController:(UIImagePickerController *)picker
             didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    ViewControllerA *userPhoto=[[ViewControllerA alloc] init];

    userPhoto.userPicture.image=chosenImage;


    [picker dismissViewControllerAnimated:YES completion:NULL];
}

它允许Use Photo按钮和应用在分配拍摄的图像时崩溃。 收到以下错误消息:

  

[ViewControllerB userPicture]:无法识别的选择器发送到实例   0x14e636160

1 个答案:

答案 0 :(得分:3)

您在此行中错误地初始化了另一个ViewControllerA对象:

ViewControllerA *userPhoto=[[ViewControllerA alloc] init];

您应该实现委托模式。在其中创建协议ViewControllerBDelegate和方法- (void)imageSelected:(UIImage *)iImage

ViewControllerA方法中将prepareForSegue:sender:设置为ViewControllerB的委托,然后在ViewControllerA中实现上述委托方法方法。从ViewControllerB开始,只需致电[self.delegate imageSelected: chosenImage]

编辑:每个OP请求的代码示例:

第1步:将以下协议添加到ViewControllerB.h

@protocol ViewControllerBDelegate <NSObject>

@required

- (void)imageSelected:(UIImage *)iImage;

@end

第2步:将委托属性添加到ViewControllerB.h

@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;

第3步:ViewControllerA.m

中实施以下方法
- (void)prepareForSegue:(UIStoryboardSegue *)iSegue sender:(id)iSender {
    ViewControllerB *vcontrollerB = (ViewControllerB *)iSender.destinationViewController;
    vcontrollerB.delegate = self;
}

第4步:ViewControllerB.m

中实施以下方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];

    [picker dismissViewControllerAnimated:YES completion:^{
        if (self.delegate && [self.delegate respondsToSelector:@selector(imageSelected:)]) {
            [self.delegate imageSelected:chosenImage];
        }
    }];
}

第5步:ViewControllerA.m

中实施以下方法
- (void)imageSelected:(UIImage *)iImage {
    self.userPicture.image = iImage;
}

作为旁注,如果不需要从userPicture外部访问,我宁愿将ViewControllerA图像视图放在我的实现文件中。