noblerare
noblerare

Reputation: 11853

Swift 3 - How do I insert TableViewCells from another view?

I am using Swift 3, Xcode 8.2.

I am trying to figure out how to insert cells into my table view from another tab of my tabbed view controller.

MyTableView

class MyTableView: UITableViewController {

    var items = ["Item 1", "Item 2", "Item 3"]

    ...

    func insertCell() {
        items.append("Item \(items.count + 1)")
        tableView.reloadData()
    }

If I create a bar button item on that table view page, I can successfully insert items, no problem. It's when I try to trigger it from another view controller that nothing happens.

Another Tab

@IBAction func triggerInsert(_ sender: Any) {
    //MyTableView().insertCell()  // this doesn't work

    //MyTableView().items.append("Item")  // these two lines don't work either
    //MyTableView().tableView.reloadData()

    // also tried setting a boolean in here to be read from MyTableView but that didn't work either
}

I'm not quite sure what the "correct" way to do this is. Any help would be greatly appreciated.

Upvotes: 0

Views: 74

Answers (1)

matt
matt

Reputation: 534925

The problem is this expression you keep trying to use:

MyTableView()

That creates a completely new and separate table view controller. But that obviously is not what you want to do. You want to talk to the existing table view controller, the one that is, as you say, another tab in the tab bar controller.

For example, if MyTableView is the first tab and OtherViewController is the second tab, then OtherViewController might say:

self.tabBarController!.viewControllers![0] as! MyTableView

...as a way of getting a reference to the existing table view controller.

Upvotes: 2

Related Questions