Swift 3 - 如何从另一个视图插入 TableViewCells? [英] Swift 3 - How do I insert TableViewCells from another view?

查看:24
本文介绍了Swift 3 - 如何从另一个视图插入 TableViewCells?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Swift 3、Xcode 8.2.

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.

另一个标签

@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.

推荐答案

问题是你一直在尝试使用这个表达式:

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.

例如,如果 MyTableView 是 first 选项卡,OtherViewController 是 second 选项卡,则 OtherViewController 可能会说:

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.

这篇关于Swift 3 - 如何从另一个视图插入 TableViewCells?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆