如何在ViewControllers之间传递一个数组,以便在UITableView(name,id)中使用?

时间:2016-10-25 11:49:26

标签: ios swift uitableview

我有LoginViewController用户登录的位置。执行此操作后,系统会提取他们所在的communities个详细信息。

这些names中的communitiesViewController将通过此部分代码传递给 let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] if let arr = json?["communities"] as? [[String:String]] { self.communitiesArray = arr.flatMap { $0["name"]!} } self.performSegue(withIdentifier: "backHome", sender: self.communitiesArray)

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

    if segue.identifier == "backHome" {
        let createViewController: ViewController = segue.destination as! ViewController
        createViewController.communities = communitiesArray
}

UITableView

然后使用ViewControllervar communities = [String]() @IBOutlet weak var communitiesTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.communitiesTableView.delegate = self self.communitiesTableView.dataSource = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.communities.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let title = self.communities[indexPath.row] let cell = UITableViewCell() cell.textLabel?.text = title return cell } 中使用此代码显示社区列表:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   self.selectedCellTitle = self.communities[indexPath.row]
    self.performSegue(withIdentifier: "showCommunitySegue", sender: self)
    }

如果用户选择社区,则会打开一个新的视图控制器' ShowCommunityViewController`并传递一个包含其名称的变量:

'id'

但是,我还希望传递此社区的"communities",该'name'也包含在LoginViewController旁边if let arr = json?["communities"] as? [[String:String]] { self.communitiesArray = arr.flatMap { $0["name"]! self.communitiesArray = arr.flatMap { $1["id"]! } } self.performSegue(withIdentifier: "backHome", sender: self.communitiesArray)

我希望我能在ShowCommunityViewController

中做出类似的事情
name

然后以某种方式传递了这个名字'并且' id'来自' ViewController'到我的新目的地id。但这并不像Syntax那样存在,只是我编造的东西!

migratesuper放在一起的最佳方式是什么?

2 个答案:

答案 0 :(得分:0)

你可以将两者拼接在一起。即。

let names = arr.flatMap { $0["name"]! }
let ids = arr.flatMap { $1["id"]! }
let communities = zip(names, ids)

答案 1 :(得分:0)

创建一个模型对象,如下所示:

class Community {
  let id: String
  let name: String

  init(id: String, name: String) {
    self.id = id
    self.name = name
  }
}

获得JSON后,创建一个Community数组,而不是仅使用String数组。

var communities = [Community]()

if let arr = json?["communities"] as? [[String:String]] {
 communities = arr.flatMap({ (candidate) -> Community?  in
    guard let id = candidate["id"], let name = candidate["name"] else { return nil }
    return Community(id: id, name: name)
})
}

我不确定你在哪里有这些数据。但是这应该传递给你的vc,在那里你可以选择社区。

在此之后,不要跟踪selectedCellTitle,而是跟踪selectedCommunity并将其分配给prepareforsegue中的vc。