在iOS中的另一个视图中打开相机

时间:2014-02-13 05:11:10

标签: ios delegates uiimagepickercontroller

如何从 MainController.m 类调用此方法并将Image传递给我的MainController

CameraController.m

- (void) openCamera {
       UIImagePickerController *picker = [[UIImagePickerController alloc]init];
       picker.delegate = self;
       picker.sourcetype = UIImagePickerContrllerSourceTypeCamera;
       [self presentViewContrller:picker animated:YES completion:nil];

}

我仍然是iOS开发的新手,是否可以使用委托?

编辑:CameraController没有笔尖。

1 个答案:

答案 0 :(得分:2)

CameraController.h中添加以下行:

@protocol CameraControllerDelegate <NSObject>
- (void)didFinishCapturingImage:(UIImage*)image;
@end

并在CameraController类(CameraController.h

中添加一个属性
@property (nonatomic, strong) id<CameraControllerDelegate> delegate;

MainController.h中,在接口实现中添加协议;像这样:

@interface MainController : NSObject <CameraControllerDelegate>

在您CameraController添加此行之前/推送MainController.m

cameraController.delegate = self;

MainController.m实施didFinishCapturingImage方法。

- (void)didFinishCapturingImage:(UIImage*)image {
    //your logic
} 

在Image Picker Controller Delegate中,添加以下行:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion: Nil];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    //this will send delegate callback to MainController
    [self.delegate didFinishCapturingImage:image];
}


编辑:第二个解决方案:

CameraController.h中创建一个属性以保留MainController对象的实例:

@property (nonatomic, strong) MainController *mainController;

将自己分配到CameraController的实例的属性mainController,您使用CameraController

cameraController.mainController = self;

编辑openCamera方法:

- (void) openCamera {
       UIImagePickerController *picker = [[UIImagePickerController alloc]init];
       picker.delegate = self.mainController; //important line
       picker.sourcetype = UIImagePickerContrllerSourceTypeCamera;
       [self.mainController presentViewContrller:picker animated:YES completion:nil];
}

并在MainController.m

中实施以下方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //your logic
}

不要忘记在UIImagePickerControllerDelegate中加入MainController.h

无需创建协议和实施协议方法。