"I am new one for iOS development now I am working on collection view. Whenever view appears I will load data with the given array, then if user did select the cell again I want to load different data again, if there is no child in the array I want to load the previous data , these all should happen in one controller. The child data can be n number of data. i have a json like this"
func numberOfSections(in collectionView: UICollectionView) -> Int { return 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
}
When view appears i loaded the data title and subtitle as "Home" and "Firm" When home tapped i want to load "Home child 1" and "Home child 2" if user again clicks the "Home child 1" cell i want to load next child if child has value.
Please guide me how to implement this ?
First you want to use Decoder
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)
Second you need to keep a stack of previous path
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")
}
When you want to move back
if let las = myStack.last {
myStack = Array(myStack.dropLast())
item = las
}
else {
print("No more prevs")
}