【问题标题】:Accessing UIViewController programmatically in Storyboard在 Storyboard 中以编程方式访问 UIViewController
【发布时间】:2014-07-28 15:18:11
【问题描述】:

我正在开发一个具有多个 ViewController 的应用程序,并且有一个特定的 ViewController“登录 ViewController”,我想从几乎每个 UIViewController 访问它,我知道我可以通过使用从每个控制器到 LoginViewController 的 segue 来实现这一点我确定这不是最好的解决方案,实现这一目标的最佳解决方案是什么?

【问题讨论】:

    标签: iphone ios objective-c storyboard


    【解决方案1】:

    使用这个...变量vc返回你正在寻找的视图控制器

      UIStoryboard *aStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
      YourViewController *vc = [aStoryboard instantiateViewControllerWithIdentifier:@"YourViewController"];
    

    【讨论】:

      【解决方案2】:

      你可能会做这样的事情

      static LoginViewController *instance; //place in the implementation
      
      - (void) viewDidLoad {
           instance = self;
      }
      
      +(LoginViewController *) getInstance { //use this method to access the instance (declare in header)
          return instance;
      }
      

      然后只需在需要访问的地方导入标题即可完成

      【讨论】:

        【解决方案3】:

        https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/UsingViewControllersinYourApplication/UsingViewControllersinYourApplication.html

        以编程方式实例化 Storyboard 的视图控制器

        清单 2-2 在同一个故事板中实例化另一个视图控制器

        - (IBAction)presentSpecialViewController:(id)sender {
            UIStoryboard *storyboard = self.storyboard;
            SpecialViewController *svc = [storyboard instantiateViewControllerWithIdentifier:@"SpecialViewController"];
        
            // Configure the new view controller here.
        
            [self presentViewController:svc animated:YES completion:nil];
        }
        

        【讨论】:

          【解决方案4】:

          我建议你应该创建一个基础视图控制器,它会被每个需要登录视图控制器的控制器子类化。 然后在你的基础 viewController 中你可以创建一个这样的方法:

          -(YourLoginViewController*)giveMeTheLoginController {
              UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboardName" bundle:nil];
              YourLoginViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"YourLoginViewControllerIdentifier"];
              return viewController;
          }
          

          如果您不想要另一个基本视图控制器,您可以在视图控制器中使用相同的方法从情节提要中获取视图控制器的新实例。

          另外,使用每个视图控制器的 segues 也是一个好方法,segues 用于定义您的导航。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-12
            • 2012-09-30
            • 1970-01-01
            • 2017-02-12
            • 2012-07-24
            • 2011-05-23
            相关资源
            最近更新 更多