ios - 将拍摄的图像分配给 ImageView

标签 ios objective-c

我有两个 View Controller 。 ViewControllerAViewcontrollerB . ViewControllerA有一个按钮可以带你ViewControllerB通过segue。
ViewControllerB允许用户通过设备相机拍照,并应将此图像分配到 ViewcontrollerA .但是我的应用程序崩溃了。

View Controller A

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

View Controller B
- (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]: unrecognized selector sent to instance 0x14e636160

最佳答案

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

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

您应该改为实现委托(delegate)模式。创建协议(protocol) ViewControllerBDelegate和方法- (void)imageSelected:(UIImage *)iImage进去。

设置您的ViewControllerA作为 prepareForSegue:sender: 中 ViewControllerB 的委托(delegate)方法,然后在 ViewControllerA 中实现上述委托(delegate)方法方法.来自 ViewControllerB只需调用[self.delegate imageSelected: chosenImage] .

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

第一步:将以下协议(protocol)添加到您的 ViewControllerB.h
@protocol ViewControllerBDelegate <NSObject>

@required

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

@end

第二步:将委托(delegate)属性添加到您的 ViewControllerB.h
@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;

第三步:在您的 ViewControllerA.m 中实现以下方法
- (void)prepareForSegue:(UIStoryboardSegue *)iSegue sender:(id)iSender {
    ViewControllerB *vcontrollerB = (ViewControllerB *)iSender.destinationViewController;
    vcontrollerB.delegate = self;
}

第四步:在您的 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];
        }
    }];
}

第五步:在您的 ViewControllerA.m 中实现以下方法
- (void)imageSelected:(UIImage *)iImage {
    self.userPicture.image = iImage;
}

作为旁注,我宁愿把 userPicture如果不需要从外部访问 ViewControllerA,我的实现文件中的 ImageView .

关于ios - 将拍摄的图像分配给 ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708873/

相关文章:

objective-c - 在 UIImageView 中区分黑白重绘和缩放以填充模式?

iphone - 使用 iPhone SDK 4 GM 运行 cocos2d

ios - XIB 中的依赖注入(inject)与异议

ios - FIRAuthUI FriendlyPix 项目错误

iphone - 尝试更改标签时出现 iOS 错误 : 'message sent to dealllocated instance' ,

ios - 动画运行时在 iOS 应用程序的主线程上暂停执行

ios - App Store 关键字 : using "trademark" keywords

ios - 你能以编程方式修改 UICollectionView的scrollDirection吗?

objective-c - CoreData 通常用作模型还是基础设施的实现细节?

ios - UIBarButtonItem 用于 UITabBarController 中的 4 个选项卡