我试图从NSObject子类中显示一个图像选择器视图控制器,但是当我在应用程序的root vc上调用presentViewController时,应用程序崩溃而没有错误消息。
我的代码在这里:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
UIViewController *root = [[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController];
[root presentViewController:picker animated:YES completion:nil];
如果我在视图控制器中运行它,它就可以正常工作。
修改
我无法使用委托,因为我正在为Unity构建一个插件,而我无法通过其他方式获取视图控制器。
我从IBAction调用当前视图控制器中的代码时注意到了崩溃:
- (IBAction)showPicker:(id)sender {
PhotoManager *manager = [[PhotoManager alloc] init];
[manager loadPhoto];
}
在这里回答评论的类代码:
PhotoManager.h:
@interface PhotoManager : NSObject <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
- (void)loadPhoto;
@end
的.m:
@implementation PhotoManager {
UIViewController *root;
}
- (void)loadPhoto {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
root = [[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController];
[root presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[root dismissViewControllerAnimated:YES completion:nil];
NSLog(@"%@", info);
}
@end
答案 0 :(得分:0)
正确的方法是创建一个协议/委托并回调呈现的viewController告诉它呈现选择器。这可以让你做更多的事情,并且是马上学习IMO的好习惯。
How do I set up a simple delegate to communicate between two view controllers?