我有两个 View Controller 。 ViewControllerA
和 ViewcontrollerB
. 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/