Reputation: 199
I want to update a UITableView that is split between a view controller all inside a UITabBar. Is it possible to update the contents of the tableview when a button has been pressed inside the view controller? I don't want to segue into the tableView just continue to update it. The logic of the tableview works with an Array so I need to be able to update that from the external view controller class as well.
Upvotes: 1
Views: 914
Reputation: 634
Yes absolutely - as long as you have a reference to the UITableView, you can simply call:
tableView.reloadData()
EDIT
Sorry, I misinterpreted the question. While the above is still valid for multiple view controllers, Duncan C is right about how it's bad practice to access the views of another view controller. For example, say I have a class ViewController1
and a class TableViewController1
. Good practice would to have something like the following:
class ViewController1: UIViewController {
private var tableView: UITableView!
func reloadTableView() {
self.tableView.reloadData()
}
}
class ViewController2: UIViewController {
func doStuff() {
// some reference to instance of first view controller
let vc = ViewController1()
// Do something that requires table view to be reloaded
vc.reloadTableView()
}
}
Hope this helps!
EDIT 2
I've added in what an implementation would like with a UITabBarController:
class MyTabBarController: UITabBarController {
var tableVC: MyTableViewController1?
var vc2: ViewController2?
override func viewDidLoad() {
super.viewDidLoad()
self.tableVC = self.storyboard?.instantiateViewControllerWithIdentifier("table vc storyboard id") as? MyTableViewController1
self.vc2 = self.storyboard?.instantiateViewControllerWithIdentifier("vc2 storyboard id") as? ViewController2
if let vc1 = self.tableVC,
let vc2 = self.vc2 {
self.viewControllers?.append(vc1)
self.viewControllers?.append(vc2)
}
}
}
class MyTableViewController1: UIViewController {
private var tableView: UITableView!
private var myArray: [AnyObject]!
func reloadTableView() {
self.tableView.reloadData()
}
func addToArray(anObject: AnyObject) {
self.myArray.append(anObject)
}
}
class ViewController2: UIViewController {
var vc2: MyTableViewController1?
func doStuff() {
// Do something that requires table view to be reloaded
vc2?.addToArray(someObject)
vc2?.reloadTableView()
}
}
Upvotes: 1
Reputation: 131501
You should not try to alter another view controller's views. That violates the principle of encapsulation - an important principle of object-oriented programming.
You should add a method that the other view controller can call.
Make sure the array that serves as the model for the table view is updated, and then send a message to the other view controller telling it to update it's table view.
The view controller that contains the table view would just call reloadData()
on it's table view in response.
Upvotes: 2