расширяемое раскрывающееся меню внутри таблицы в swift4

Я пробовал расширяемый раскрывающийся список внутри таблицы в swift4, но не работал с моим кодом ниже. если я изменил класс пользовательской модели на String, он работает. мое требование использовать ниже пользовательского класса модели. пожалуйста, проверьте мой код ниже.

class ExpandViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ExpandableHeaderViewDelegate {
        var empDetails = [EmpWorking]()
        var hiredDetails = [Hired]()

        @IBOutlet weak var tableView: UITableView!
        var sections = [SectionData]()

        override func viewDidLoad() {
            super.viewDidLoad()
            loadData()
            // Do any additional setup after loading the view.
        }

        func numberOfSections(in tableView: UITableView) -> Int {
            return sections.count
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return sections[section].emp.count
        }

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 44
        }
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            if(sections[indexPath.section].expanded){
                return 80
            }
            else{
                return 0
            }
        }
        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
            return 2
        }

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            var header = ExpandableHeaderView()
            header.customInit(title: sections[section].genre, section: section, delegate: self)
            return header
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "labelCell", for: indexPath) as! expandDataCell
            cell.lbl1.text = "\(sections[indexPath.section].emp![indexPath.item].name)"
            cell.lbl2.text = "\(sections[indexPath.section].emp![indexPath.item].dept)"
            return cell as expandDataCell
        }

        func toggleSection(header: ExpandableHeaderView, section: Int) {
            sections[section].expanded = !sections[section].expanded
            tableView.beginUpdates()
            for i in 0 ..< sections[section].emp.count
            {
                tableView.reloadRows(at: [IndexPath(row: i, section: section)], with: .automatic)
            }
            tableView.endUpdates()
        }

    func loadData(){
        let url = "http://www.json-generator.com/api/json/get/ccgFfBFWqa?indent=2"
        guard let resourceString = URL(string: url) else{return}
        let decoder = JSONDecoder()
        URLSession.shared.dataTask(with: resourceString) { (data, response, err) in
            guard let data = data else{return}
            do{
            let expandData = try decoder.decode([ExpandModel].self, from: data)
                print("Expand Data:\(expandData)")
                for i in expandData[0].emp_working{
                    print("i=\(i)")
                    self.empDetails.append(i)
                }
                for j in expandData[0].emp_recent_hired{
                    self.hiredDetails.append(j)
                }

                DispatchQueue.main.async {
//                    self.sections = [SectionData(genre: "Employee Working", emp: self.empDetails, expanded: false),
//                    SectionData(genre: "Employee Hired", emp: self.hiredDetails, expanded: false)
//                    ]
                    self.tableView.reloadData()
                }
            }
            catch let jsonErr{
                print("Expand Data Err:\(jsonErr)")

            }
        }.resume()

    }

}

struct ExpandModel: Codable{
    let emp_working: [EmpWorking]
    let emp_recent_hired: [Hired]
}

struct EmpWorking: Codable{
    let dept: String
    let name: String
}

struct Hired: Codable {
    let name: String
    let qualification: String
}


struct SectionData {
        var genre: String!
        var emp: [EmpWorking]!
        var expanded: Bool!

        init(genre: String, emp: [EmpWorking] = [], expanded: Bool)
        {
            self.genre = genre
            self.emp = emp
            self.expanded = expanded
        }
}

Требуемый результат:

Работающий сотрудник > Нанятый сотрудник >

если нажать «Рабочий сотрудник», он отобразит следующий вывод:

Сотрудник, работающий с Джоном Вебом

Алекс Мобайл


person Ajay    schedule 11.12.2019    source источник
comment
Ваш вопрос не ясен. Можете ли вы предоставить больше информации о том, чего вы хотите достичь? Хотите 2 раздела в табличном представлении Exp work & Hired, и если щелкнуть по нему, отобразится ячейка ... в основном расширяться и сворачиваться?   -  person Milan    schedule 27.12.2019


Ответы (1)


дизайн раскадровки

на изображении выше вы можете видеть две метки, где будут отображаться динамические данные. При каждом щелчке индекса ячейки ячейка будет расширяться, как вы видите на экране ниже.

простое представление выглядит следующим образом

После использования ячейки она будет выглядеть так

поэтому все, что вам нужно сделать, это сделать: - сначала создайте переменную для хранения индекса didselectrowat, например: -

var int_row = Int()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        int_row = indexPath.row . // save the index path
        yourTableViewName.reloadData() // reload the table
} 

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
     if int_row == indexPath.row { // when you tap on cell then it will expend 
     the cell
        return UITableView.automaticDimension
    } else {
        return 48 // at this time only show your uppar labal only 
    }
   }
person Vipin Pareek    schedule 04.02.2020