““我是iOS开发的新手,现在我正在收集视图。每当出现该视图时,我都会使用给定的数组加载数据,然后如果用户再次选择了该单元格,要再次加载不同的数据,如果数组中没有子级,我想加载先前的数据,这些都应该在一个控制器中发生。子级数据可以是n个数据。我有一个像这样的json” >
func numberOfSections(在collectionView中:UICollectionView)-> Int { 返回1 }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return item.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ProofAddressCell
cell.nameLabel.text = item[indexPath.row]["address_title"] as? String
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let childItem = item[indexPath.row]["child"] as? [[String: AnyObject]] {
if childItem.count > 1 {
item = childItem
let addItems: [[String: AnyObject]]!
// addItems.append(item)
collectionView.reloadData()
}
else {
print("There is no option to show")
let alert = UIAlertController(title: "Welcome", message: "No child available", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion:{ () in
self.moveBack()
})
}
}
else {
print("There is no option to show")
let alert = UIAlertController(title: "Welcome", message: "No child available", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion:{ () in
self.moveBack()
})
}
}
func moveBack() {
print("have to move back")
//item = childArray
}
出现视图时,我将数据标题和副标题分别加载为“主页”和“固定” 轻按首页时,如果用户再次单击“首页子项1”单元格,则我想加载“首页子项1”和“首页子项2”,如果子项有值,我要加载下一个子项。
请指导我如何执行此操作?
答案 0 :(得分:1)
首先要使用解码器
struct Root: Codable {
let captureMethod, addressTitle, addressSubtitle: String
let addressRequired: Int
let poafilename: String
let child: [Root]
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = decoder.decode(Root.self,from:data)
item.append(res)
第二,您需要保留一堆先前的路径
var myStack = [[Root]]()
var item = [Root]()
if item[indexPath.row].child.count > 1 {
myStack.append(item)
item = item[indexPath.row].child
}
else {
print("No more childs")
}
要后退时
if let las = myStack.last {
myStack = Array(myStack.dropLast())
item = las
}
else {
print("No more prevs")
}