ios - 在函数 swift 中使用 presentviewcontroller

标签 ios xcode swift2 uiwindow presentviewcontroller

我试图在函数运行后使用它来呈现 View Controller ,因此将其包含在函数中

let window = UIWindow()
let rootViewController = window.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("EmployeeTBCIdentifier")
rootViewController?.presentViewController(setViewController, animated: true, completion: nil)

它没有做任何事情,如果我在 viewDidLoad() 中使用它它就会起作用

这是主要思想,是否可以根据此示例使用补全,

func logInType(completion(Void1, Void2)->()) {
if login == employer{
    void1
}else if login == employee{
    void2
    }
}

当使用函数时我想返回这个

func logInType{(void1, void2) -> void in
void1 = self.presentview //I want to push view to another if this code executed
void2 = self.presentview //same idea
}

更新:代码正在运行,但没有推送到识别的 View Controller 。

dispatch_async(dispatch_get_main_queue()){
                        let window = UIWindow()
                        let rootViewController = window.rootViewController
                        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
                        let setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("EmployeeTBCIdentifier")
                        rootViewController?.presentViewController(setViewController, animated: true, completion: nil)
                    }

最佳答案

在我看来,您获取 rootViewController 的方式可能存在问题.我认为 let window = UIWindow()调用将返回一个新的 UIWindow对象而不是你想要的是 Root View Controller (和你的应用程序)与之关联的窗口。继续这个,rootViewController将是 nil和您的可选链调用 rootViewController?.presentViewController(setViewController, animated: true, completion: nil)不会做任何事情。通过 rootViewController!.presentViewController(setViewController, animated: true, completion: nil) 使用显式展开你应该会看到错误

要纠正,请通过其他方式获取正确的 UIWindow,或者从 UIAppDelegate或者从另一个 View Controller 使用 OtherViewController.view!.window!

关于ios - 在函数 swift 中使用 presentviewcontroller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959298/

相关文章:

iphone - 链接到通用静态库(设备/模拟器)是否在为 arm 生成的二进制文件中包含 x86 代码?

ios - 如何隐藏 Storyboard中的图像/标签以在我们运行应用程序时显示?

iphone - 为较旧的 SDK 部署 iOS 应用程序时,如何测试它?

objective-c - NSTimer、NSBlockOperation NSInvocation 还是 NSOperation?

swift - 从容器 View 访问导航栏

ios - 带有 -ObjC 链接器标志的 Firebase、Fabric 和 Crashlytics,没有 Cocoapods iOS

swift - Segue 未在 Swift 中发送正确的单元格信息

objective-c - 在具有多个离散子屏幕的 UIViewController 中使用动画的正确方法是什么?

ios - 从 SQLite 检索行花费太多时间

ios - 为什么我的 UITableViewCell 中的多行 UILabel 在第一次加载时被截断,但在滚动时会自行更正?