Root View Controller Swift

醉酒当歌 提交于 2020-02-08 09:15:36

问题


I have a function in my app delegate which appends an item to an array in my a file named ViewController.swift, and then I want to reload a tableview in that same file. I attempt to do so like so:

let vc = ViewController()
let navigationController = UINavigationController(rootViewController: vc)
window!.rootViewController = navigationController
println(vc.messages)

//1        vc.messages.append(message.data.message as! String)
//2        vc.MessageTableView?.reloadData()

The lines numbered 1,2 are where I set breakpoints. It appears to break after line numbered 2.

The exact error I get is

fatal error: unexpectedly found nil while unwrapping an Optional value

I believe my problem is that I am setting the root view controller incorrectly.

Edit #1

Window is declared up top.

If i run my code like this:

    let vc = ViewController()
    messages.append(message.data.message as! String)
    vc.MessageTableView?.reloadData()
    println(messages)

Then I can see that the correct data is put into the array (Which i made global for this scenario) but the table does not get updated in the View controller.


回答1:


You have to reload data inside your ViewController Put the reload inside viewDidAppear() or sth like that

It's an error because you just init a controller, but your views is not ready yet, they are being initialized. After viewDidLoad, you can call your views, but not before.

So that's why your table is nil

Beside that, why do you need to reload your table even when you don't see it, right ?




回答2:


What is the implementation of your delegate function? After you put the tableview in the storyboard,You have to connect the tableview to the ViewController.swift. Control drag from the tableview to the top of the viewcontroller (the yellowcircle) , there will be a black popup , do that two times and for each time click on datasource and delegate. Then in the viewcontroller.swift file implement the functions they show in this tutorial. You don't have to modify the AppDelegate.swift file!

https://www.weheartswift.com/how-to-make-a-simple-table-view-with-ios-8-and-swift/




回答3:


if you want you viewcontroller to be the rootviewcontroller al you have to do is click on the viewcontroller in storyboard and then in the utilities-> attributes inspector -> check the box "is initial view controller"

https://www.dropbox.com/s/qfd9jqeos7ueq1w/Screen%20Shot%202015-06-25%20at%207.40.46%20PM.png?dl=0



来源:https://stackoverflow.com/questions/31062108/root-view-controller-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!