以编程方式从UIView加载View Controller

时间:2018-01-19 01:30:55

标签: ios swift uiview viewcontroller

我在类中使用以下内容来调用UIViewController。 UIViewController加载,但在加载后变得无响应。

let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

let homeC = storyboard.instantiateViewController(withIdentifier: 
"ViewJoeProfileController") as? ViewJoeProfileController
    if homeC != nil {
        homeC!.view.frame = (self.window!.frame)
        self.window!.addSubview(homeC!.view)
        self.window!.bringSubview(toFront: homeC!.view)
    } 
}

任何使UIViewController加载响应的建议都会有所帮助!

2 个答案:

答案 0 :(得分:0)

如果您特别想要添加到窗口,您应该以正确的方式执行并添加整个ViewController:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    guard let window = UIWindow(frame: UIScreen.mainScreen().bounds) else { return true }
    if let homeC = storyboard.instantiateViewController(withIdentifier: "ViewJoeProfileController") as? ViewJoeProfileController {
        window.rootViewController = mainViewController
        window.makeKeyAndVisible()
    }

    return true
}

但老实说,这种结构似乎仍然不正确。为什么要向窗口添加视图,而不是使用初始视图控制器,然后添加到其视图,或者转到不同的ViewControllers?。

答案 1 :(得分:0)

尝试使用这个我需要创建根视图控制器

let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "ViewJoeProfileController") as! ViewJoeProfileController
let nav = UINavigationController(rootViewController: vc)
nav.isNavigationBarHidden = true
self.window?.rootViewController=nav
self.window?.makeKeyAndVisible()