jonthornham
jonthornham

Reputation: 3335

Initializing a ViewController when you aren't using Nib Files

I am converting a project that use to use nib files to a project where I am using Storyboards. The app has a home screen (HomeVC) that is loaded into a navigation controller. When the app launches it starts a data handler that pulls rss data from a number of sources and stores them in CoreData. In the HomeVC I was instantiating the next view in the stack (FeedVC) so that I could call a reloadData() method on it when the data handler finished downloading the feeds. To instantiate FeedVC I wrote the following code when I set up the data handler in the HomeVC.

// This initializes the Feed VC for use later in the VC
    FeedViewController *view = [[FeedViewController alloc] initWithNibName: @"FeedViewController" bundle: nil];
    self.feedViewController = view;

When the data handler finished I reloaded the table view with the following code.

[self.feedViewController.feedsTableView reloadData];

This worked well.

The new project is coded in Swift and as I mentioned is using Storyboards. My problem is that when I call

self.feedViewController!.feedsTableView.reloadData()

The compiler tells me that it is nil. This is understandable since I no longer have a nib to instantiate the view with. How can I instantiate the FeedVC when I am using a Storyboard instead of nib files?

Attempted Solution

Here is where I named the VC.

enter image description here

Here is the code I entered into the method that sets up the data handler.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("FeedViewController") as! FeedViewController
        self.feedViewController = vc

Here is my storyboard name.

enter image description here

Maybe the issue is the feedsTableView and not the feedViewController. I have feedsTableView declared as an option in FeedViewController.

@IBOutlet weak var feedsTableView: UITableView!

Take care,

Jon

Upvotes: 0

Views: 31

Answers (1)

Victor Sigler
Victor Sigler

Reputation: 23449

First of all you have to set the Storyboard ID in the Identity Inspector using the Interface Builder :

enter image description here

And then you can call the following code wherever you want to instantiate your FeedViewController :

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("nameOfYouPut") as! FeedViewController

I hope this help you.

Upvotes: 1

Related Questions