【问题标题】:Connect Two Related TableViewController Arrays连接两个相关的 TableViewController 数组
【发布时间】:2017-07-02 18:49:46
【问题描述】:

我知道标题有点含糊,所以让我解释一下。我有两个 TableViewController,分别称为 MainTableViewControllerDetailTableViewController。此外,我创建了多个数组,它们在思想上是通过层次结构连接的:

let maincCarChoice = ["Toyota", "Nissan", "Ford"]

let toyotaCarChoice = ["Prius", "Camry", "Etios"]
let nissanCarChoice = ["Altima", "Maxima", "Rogue"]
let fordCarChoice = ["Fusion", "Focus", "Explorer"]

我设法用mainCarChoice 数组填充MainTableViewController 并实现segue,当触摸三个选项之一时,它会转到DetailTableViewController。话虽如此,但我不确定如何根据用户在MainTableViewController 中的选择使用相应的数组填充DetailTableViewController。任何帮助将不胜感激,并提前感谢您。

【问题讨论】:

  • 你应该有一个从 maincCarChoice 到 toyotaCarChoice、nissanCarChoice 等的数据映射。然后根据映射分配各个数组。
  • 您好,对不起,我是编程新手。您介意向我解释一下什么是数据映射,或者将链接发送给我可以阅读的地方吗?
  • 查看@Moe Abdul-Hameed 的答案。这是一种方法。

标签: ios arrays swift uitableview


【解决方案1】:

实现这一点的一种方法是向DetailTableViewController 添加一个字符串成员数组,如下所示:

var vehiclesArray: [String]?

这个数组应该作为DetailTableViewController内的表格视图的数据源。

现在,在MainTableViewController

首先,添加一个包含汽车品牌和型号的字典:

var vehiclesDictionary = ["Toyota" : ["Prius", "Camry", "Etios"],
                          "Nissan" : ["Altima", "Maxima", "Rogue"],
                          "Ford" : ["Fusion", "Focus", "Explorer"]]

然后像这样覆盖prepare方法:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "YourIdentifier" {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                let selectedVehicle = vehicles[indexPath.row]

            if let nextScene = segue.destination as? DetailTableViewScene {
                nextScene.vehiclesArray = self.vehiclesDictionary[selectedVehicle]
            }
        }
    }
}

【讨论】:

  • 这也可以是此类中的字典映射,键为“Toyota”,值为其数组。那么这个函数就可以简化了。
  • 你说得对,谢谢!我更新了代码以反映您的建议。
  • 嘿萌,感谢您的回复。如果每个车型都有我想要访问的特定属性,那我会怎么做?例如,单击 Nissan mainTableViewController 后,一旦表格填充了 "Altima, "Maxima", "Rogue",我想在表格视图的右侧添加第一个车型年份日期。
  • “第一个模型年份日期”是什么意思?您从哪里获得这些信息?
猜你喜欢
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
相关资源
最近更新 更多