ios - 如何在 ViewController 之间传递数组以在 UITableView 中使用(名称,id)?

标签 ios swift uitableview

我有用户登录的LoginViewController。执行此操作后,将从他们所在的社区获取详细信息。

这些社区名称通过以下代码段传递给ViewController:

 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
}

然后使用 UITableViewViewController 中使用此代码显示社区列表:

var 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

}

如果用户选择一个社区,则会打开一个新的 View Controller “ShowCommunityViewController”并传递一个包含其名称的变量:

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

但是,我还想传递该社区的 '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)

然后以某种方式将“name”和“id”一起从“ViewController”传递到我的新目的地 ShowCommunityViewController。但这并不作为语法存在,只是我编造的东西!

同时传递nameid的最佳方式是什么?

最佳答案

您可以将两者压缩在一起。即

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

关于ios - 如何在 ViewController 之间传递数组以在 UITableView 中使用(名称,id)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239169/

相关文章:

ios - 检测用户是否退出 MKCircle | map 套件

ios - 在 View Controller 中快速/启用编辑模式

ios - 在 UITableView 的标题栏下添加阴影

iOS 表格标题和单元格之间的快速边距

ios - GameScene.sks 和 GameScene.swift

swift - swift 中的编程按钮不起作用

ios - 使用 Xib 在 Tableview header 中快速重新加载 CollectionView

ios - 如何在运行时在 Objective-C 中查找字符串常量?

ios - 在 iOS (Swift) 中集成 Stripe SDK

ios - 将视频分成 30 秒的 block Ios swift 5