我有用户登录的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
}
然后使用 UITableView
在 ViewController
中使用此代码显示社区列表:
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
。但这并不作为语法存在,只是我编造的东西!
同时传递name
和id
的最佳方式是什么?
最佳答案
您可以将两者压缩在一起。即
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/