问题描述
我只想在选择 collectionView 的项目时将项目 id 传递给下一个视图控制器。
这里存储我从 API 获取的数据
这是一些代码 -->
var posts = [[String: Any]]()
func apicall() {
let Url = String(format: "http:example.com")
guard let serviceUrl = URL(string: Url) else { return }
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json",forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request) { (data,response,error) in
if let response = response {
print(response)
}
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data,options: []) as? [String : Any]{
self.posts = (json["data"] as? [[String : Any]])!
dispatchQueue.main.async() {
self.collectionView.reloadData()
}
}
} catch {
print(error)
}
}
}.resume()
}
现在我得到了数据,我想传递只被选中的那个项目的项目 id
@IBAction func onClickNext(_ sender: Any) {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
self.navigationController?.pushViewController(controller,animated: true)
}
这里是 didSelectItemAt 索引路径的代码
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! secondCollectionViewCell
}
解决方法
始终从模型(数据源数组)中获取数据,而不是从视图
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
let item = self.posts[indexPath.item]
let id = item["id"]
// do things with id
}
,
那一刻,如果您启用了选择,集合视图将能够返回集合视图中所有选定单元格的 IndexPath
。
请在 UICollectionView
var indexPathsForSelectedItems: [IndexPath]? { get }
apple documentation for indexPathForSelectedItems
然后在您的 @IBAction func
处执行此操作
@IBAction func onClickNext(_ sender: Any) {
// logic to grab the id from self.posts using the selected indexPaths ie.
let selectedItems = self.collectionView.indexPathsForSelectedItems ?? []
let ids = selectedItems.compactMap { self.posts[$0.row] }
let controller = self.storyboard?.instantiateViewController(withIdentifier:
"secondViewController") as! secondViewController
controller.selectedIds = ids // all the selected ids
self.navigationController?.pushViewController(controller,animated: true)
}
所以你应该做类似的事情,我不知道你的 self.posts
属性中的数据结构是什么样的,但上面的代码给了你一个想法。为了简化这一过程,请尝试在操场中运行以下代码并查看结果。
import UIKit
let posts: [String] = ["Carrot_Post","Pencil_Post","Dish_Post","Data_Post","iOS_Post","Kitties_Post","VideoGamesPost","Bitcoin_Post"]
let selected: [Int] = [1,3,5]
let items: [String] = selected.compactMap({ posts[$0] })
print(items) // output: ["Pencil_Post","Carrot_Post","Kitties_Post"]
希望对您的问题有所帮助。