Разверните и сверните многоуровневые разделы в uitableview swift4 - PullRequest
0 голосов
/ 10 апреля 2019

Я хочу развернуть и свернуть многоуровневый массив в uitableview, как показано ниже:

  • Cat1
    • SubCat1
      • Info 1
      • Info 2
    • SubCat2
      • Информация 1
      • Информация 2
    • SubCat3
      • Информация 1
      • Информация 2
  • Cat2
    • SubCat1
      • Информация 1
      • Информация 2

Для этой цели я сделал следующий код.

struct CellData {
var opened = Bool()
var subCatTitle = String()
var subCatList = [String]()
}
struct MainModel {
var opened = Bool()
var categoryTitle = String()
var categoryList = [CellData]()
} 

Я составил список

 @IBOutlet var expandableThreeStageTableView: UITableView!
    var arrayList = [CellData]()
    var expandableList = [MainModel]()

func loadData(){
    arrayList.append(CellData(opened: false, subCatTitle: "SubCat1", subCatList: ["Info1","Info2","Info3"]))
    arrayList.append(CellData(opened: false, subCatTitle: "SubCat2", subCatList: ["Info1","Info2","Info3"]))
    arrayList.append(CellData(opened: false, subCatTitle: "SubCat3", subCatList: ["Info1","Info2"]))
    arrayList.append(CellData(opened: false, subCatTitle: "SubCat4", subCatList: ["Info1"]))

    expandableList.append(MainModel(opened: true, categoryTitle: "Cat1", categoryList: arrayList))
    expandableList.append(MainModel(opened: false, categoryTitle: "Cat2", categoryList: arrayList))
    expandableList.append(MainModel(opened: false, categoryTitle: "Cat3", categoryList: arrayList))
}

И делегируйте, методы источника данных приведены ниже

extension TextFieldAsSearchVC : UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
        return expandableList.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
Int) -> Int {
        if expandableList[section].opened{
            if expandableList[section].categoryList[section].opened{
                return 
expandableList[section].categoryList[section].subCatList.count////which extra count should return here
            }else{
                print("COUNT ",expandableList[section].categoryList.count)
                return expandableList[section].categoryList.count + 
1///here +1 is for catname + subcatname

            }
        }else{
            return 1
        }
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {

        if indexPath.row == 0{
            let cell = 
expandableThreeStageTableView.dequeueReusableCell(withIdentifier: 
"TextFieldAsSearchVCCell", for: indexPath) as! TextFieldAsSearchVCCell
            cell.lblValue.text = 
expandableList[indexPath.section].categoryTitle
            return cell
        }else if indexPath.row <= 
expandableList[indexPath.section].categoryList.count{
             let cell = 
expandableThreeStageTableView.dequeueReusableCell(withIdentifier: 
"SectionDataCell", for: indexPath) as! SectionDataCell
            cell.rowLabel.text = 
expandableList[indexPath.section].categoryList[indexPath.row - 
1].subCatTitle
            return cell
        }
        else{
            let cell = 
expandableThreeStageTableView.dequeueReusableCell(withIdentifier: 
"SectionDataCell", for: indexPath) as! SectionDataCell
  cell.rowLabel.text = 

 expandableList[indexPath.section].categoryList[indexPath.row].
subCatList[indexPath.row]//how to access rows in subcategories
            return cell
        }
    }
}
extension TextFieldAsSearchVC : UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: 
IndexPath) {
        if indexPath.row == 0{
            if expandableList[indexPath.section].opened{
                expandableList[indexPath.section].opened = false
                //now reload the section
                let sections = IndexSet(integer: indexPath.section)
                expandableThreeStageTableView.reloadSections(sections, 
with: .automatic)
            }else{
                expandableList[indexPath.section].opened = true
                //now reload sections
                let sections = IndexSet(integer: indexPath.section)
                expandableThreeStageTableView.reloadSections(sections, 
with: .automatic)
            }

        }else {
            if 
expandableList[indexPath.section].categoryList[indexPath.row].opened{

expandableList[indexPath.section].categoryList[indexPath.row].opened = 
false
                expandableThreeStageTableView.reloadRows(at: 
[IndexPath(index: indexPath.row)], with: .automatic)
            }else{

expandableList[indexPath.section].categoryList[indexPath.row].opened = 
true
                expandableThreeStageTableView.reloadRows(at: 
[IndexPath(index: indexPath.row)], with: .automatic)
            }
        }
    }
}

Из приведенного выше кода я могу развернуть и свернуть Категориино не подкатегории .. Когда я пытался нажать на подкатегории, это выдает мне ошибку

*** Terminating app due to uncaught exception 
'NSInternalInconsistencyException', reason: 'Invalid index path for use 
with UITableView. Index paths passed to table view must contain exactly 
two indices specifying the section and row. Please use the category on 
NSIndexPath in NSIndexPath+UIKitAdditions.h if possible.'

Как бороться с таким типом логики?

1 Ответ

0 голосов
/ 10 апреля 2019

В этой строке вы видите конкретную ошибку:

expandableThreeStageTableView.reloadRows(at: [IndexPath(index: indexPath.row)], with: .automatic)

Для IndexPath нужны оба значения: row и section;Вы только предоставляете ряд.Так что должно быть что-то вроде этого:

expandableThreeStageTableView.reloadRows(at: [IndexPath(row: indexPath.row, section: indexPath.section)], with: .automatic)

Если вам действительно нужно только перезагрузить текущий indexPath, просто назовите его так:

expandableThreeStageTableView.reloadRows(at: [indexPath], with: .automatic)

Это исправит полученную ошибку, но я не знаю, решит ли это вашу проблему или нет.

...