расширяемый выпадающий список внутри таблицы в swift4 - PullRequest
1 голос
/ 11 декабря 2019

Я пытался, раскрывающийся раскрывающийся список внутри таблицы в 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
        }
}

Требуемый вывод:

Работа с сотрудником> Наемный работник>

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

Работающий работник V John Web

Алекс Мобайл

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...