I have a ViewController
with a Container View
that has an embedded TableViewController
.
Now i would like to access the TableView
in the ViewController
, how can i make an outlet for that?
I tried to add the Container View as an outlet, but i can't access the embedded TableViewController
.
You can't make an outlet directly because the table view is in a different scene (view controller), but you can access the tableview once you have a reference to the UITableViewController
instance. There are a couple of different ways of doing that.
First, you can use the childViewControllers
property of your UIViewController
subclass. If you know that there is only a single child then you can access it directly, otherwise you need to determine which is the correct child, say by looping through the array.
let myTableViewController = self.childViewControllers[0] as! UITableViewController
let theTableView = myTableViewController.tableView
The second option is to access the UITableViewController
during the embed segue. If you click on the embed segue in your storyboard you can give it an identifier as with any other segue. Then you can implement prepareForSegue
and grab the embedded UITableViewController
instance -
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "tableviewEmbed") {
let myTableViewController = segue.destinationViewController as! UITableViewController
let theTableView = myTableViewController.tableView
}
}
Personally, I prefer this second approach as I think it is 'cleaner'
Create outlet in child View Controller and access it using self.childViewControllers.lastObject (assuming you only have one child, otherwise use objectAtIndex:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With