在tableViewController

时间:2017-06-13 15:56:44

标签: ios swift uitableview static

我是Swift和iOS开发的新手,我想看看是否有更好的方法来完成以下任务:

在我的应用程序中,我有一个表存储为[someObject]并由tableViewController管理。我在tableViewController中编写了管理表的所有逻辑(添加对象,删除对象等)。但是,tableView本身只能从表中删除对象。我想从应用程序的不同部分以编程方式添加密钥。这样做的问题是从tableViewController外部访问表示表的数组。

我想到的最好的解决方案是使数组静态,这样我就可以在没有tableViewController实例的情况下对其进行修改(当需要将对象添加到表中时,tableViewController不会出现在导航堆栈中)。

我也不想转向tableViewController。表格的添加应该在幕后进行。

就像我说的,我是Swift和iOS开发的新手,所以我想看看是否有更好的方法来实现这一目标。如果我不需要,我宁愿不使用静力学。

2 个答案:

答案 0 :(得分:0)

您不应该使用静态数组,但是您也不应该有多个类来管理同一个对象。 您的Array应由Manager类管理,并且此管理器可由多个类访问。你的tableViewController不应该能够删除对象,但是可以调用执行这些更改的管理器

答案 1 :(得分:0)

你正在努力做更多的事情。 Apple构建了UITableViewControllers,其中包含您正在寻找的许多功能。

首先在故事板中为标签为123的单元格添加一个标签。然后是另一个viewController,其中一个空数组与tableViewController中的数组兼容。

在每个viewController的身份检查器中,确保添加文件名并按Enter键。

还可以通过查看main.storyboard中tableViewCell的属性来设置reuseidentifier,在字段Identifier中输入“cell”(无引号)。

从tableViewController1开始显示你的数组(我假设它是预加载的。你没有提到其他情况)使用数据源方法

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return yourObjects.list.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let label = cell.viewWithTag(123) as? UILabel
    label?.text = yourObjects.list[indexPath.row]

    return cell
}

如果您不打算使用segues,我强烈建议您使用navigationController。它们是“iOS体验”的主要部分,使您尝试完成的任务变得更加容易。有很多方法可以做到这一点,但这是一个相当简单的方法。 在你的委托方法

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let yourNextVC = storyboard?.instantiateViewController(withIdentifier: "nextVC") as! TheNextVC
    navigationController?.pushViewController(yourNextVC, animated: true)
    yourNextVC.arrayName = yourObjects.list[indexPath.row]
    tableView.deselectRow(at: indexPath, animated: false)
}

最后一种方法是将数组从此表传递到下一个viewController,您可以在其中编辑它或执行您想要的任何操作。