简体   繁体   中英

Root View Controller Swift

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.

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/

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM