我有 n
个不同的 ViewController
,因此我想在 Objective-C 中呈现来自任何其他 ViewController 的
PresentViewController
我目前的表现:
所以目前我正在所有 ViewController 中导入“PresentViewController.h”
,然后调用以下代码来呈现它:
NSString * storyboardName = @"MainStoryboard";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
PresentViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];
但是通过这种方式,我必须将 "PresentViewController.h"
文件导入到所有其他 ViewControllers
中,这看起来非常烦人的工作。
我在寻找什么:
是否有其他方法可以从特定位置呈现 PresentViewController,并且可以在需要时从任何 ViewController 呈现它?
最佳答案
如果这确实是您所拥有的全部代码,那么您就不会使用它特有的 PresentViewController 做任何事情,因此请不要在代码中提及它的名称:
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];
如果您没有在代码中提及它,则不需要导入它。
但显然,如果您使用 PresentViewController 执行某些操作,例如调用它的方法,那么事情会更加复杂。您可以转换为id
,在这种情况下,您可以调用任何方法,前提是编译器知道它(也称为非正式协议(protocol))。但一般来说,硬着头皮进行导入会更好。
关于ios - 从许多不同的 ViewController 中呈现 ViewController 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311098/