在Swift中访问AppDelegate中的UIViewCotroller

时间:2017-06-13 09:15:51

标签: ios swift

我想访问AppDelegate中的UIViewcontroller。层次结构显示在此处:enter image description here

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let navController = self.window!.rootViewController as! UINavigationController
    let tabController = navController.topViewController as! UITabBarController

    var postController =  tabController.topViewController as! UITableViewController  
    // It is incorrect. has no member of topViewController

    return true
}

5 个答案:

答案 0 :(得分:1)

if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
    while let presentedViewController = topController.presentedViewController {
        topController = presentedViewController
    }

    // topController should now be your topmost view controller
}

答案 1 :(得分:1)

你有没有试过像:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let navController = self.window!.rootViewController as! UINavigationController
    let tabController = navController.topViewController as! UITabBarController
    var postController =  tabController.viewControllers[0]
    // It is incorrect. has no member of topViewController
    return true
}

选项卡栏控制器管理ViewControllers列表。在这种情况下,您需要列表中的第一个。请注意语法可能有点不对,因为我没有太多快速的经验!

var postController =  tabController.viewControllers[0]

这是我改变的部分。

答案 2 :(得分:1)

问题是您不必从AppDelegate访问您的控制器,这是您的应用程序架构中的错误。 AppDelegate应仅用于应用程序的生命周期(启动/激活/停用/推送通知/ ...) 你为什么要在这里访问你的viewController?

答案 3 :(得分:0)

你已经使用故事板进行了转发, 你所要做的就是:

MenuBar.Command tablecommand = new MenuBar.Command() {
        public void menuSelected(MenuItem selectedItem) {
            output.setValue("clean components");
            layout2.removeComponent(name);
            layout2.removeComponent(name2);
            layout2.removeComponent(button);
            layout2.removeComponent(cp);

            //layout2.removeComponent(grid);
            //if layout2 !contains grid

            layout2.addComponent(grid,1,2);

        }
    };

答案 4 :(得分:-1)

您可以使用故事板标识符来访问视图控制器

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "storyboardIdentifier")