Вставка и удаление строк для эффекта расширения и свертывания для просмотра таблицы

У меня проблема с источником данных. причина: «попытка вставить строку 0 в раздел 0, но после обновления в разделе 0 осталось только 0 строк».

Я пытался развернуть и свернуть раздел 1 моего табличного представления. Когда мне впервые представили контроллер представления, я могу развернуть его, а затем свернуть, но когда я пытаюсь развернуть его во второй раз, он вылетает. Я пытаюсь добавить + 1, когда он расширяется в numberOfRows, но это тоже дает сбой. не знаю, что я делаю неправильно и что мне нужно добавить, чтобы это сработало.

Изменить * Когда я сначала нажимаю, чтобы развернуть раздел, внутри numberofRowsInSection запускается оператор if isExpanded == false, который дает мне section.count - 1. Но почему это выполняется и возвращает мне строку? Кажется, моя проблема как-то связана с этим, но IDK исправляет.

var sectionArray = [ ExpandableCell(isExpanded: false, section: [""])
]


@objc func handleExpandClose(button: UIButton) {
    let indexPath = IndexPath(row: 0, section: 0)

    let isExpanded = sectionArray[0].isExpanded
    if isExpanded {
        sectionArray[0].section.removeAll()
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.endUpdates()
    } else {
        sectionArray[0].section.append("")
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .fade)
        tableView.endUpdates()

    }
    sectionArray[0].isExpanded.toggle()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if section == 0 && sectionArray[0].isExpanded {
        return sectionArray[0].section.count
    } else if section == 0 && sectionArray[0].isExpanded == false {
        return sectionArray[0].section.count - 1
    }

    else if section == 1 {
        return 1
    }
    return 0
}

person Kenny Ho    schedule 06.02.2019    source источник


Ответы (1)


когда приложение запускает это

if section == 0 && sectionArray[0].isExpanded == false

запускается, поэтому количество строк равно 0 в соответствии с ectionArray[0].section.count - 1 , затем, когда вы нажимаете дескриптор действияExpandClose , запускается else

} else {
sectionArray[0].section.append("")
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .fade)

в нем вы добавляете данные во внутренний массив внутри единственного объекта, поэтому при вставке основной массив dataSource sectionArray не изменился, следовательно, сбой


class TableViewController: UITableViewController {

    var sectionArray = [ExpandableCell(),ExpandableCell(),ExpandableCell()]


    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem

        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        // simulate collapse action
        DispatchQueue.main.asyncAfter(deadline: .now() + 4) {

            self.sectionArray[0].isExpanded = false

            self.tableView.reloadData()
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return sectionArray.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sectionArray[section].isExpanded ? sectionArray[section].content.count : 0
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = sectionArray[indexPath.section].content[indexPath.row]

        return cell
    }


}



struct ExpandableCell {

    var isExpanded = true

    var content = ["1","2","3"]
}
person Sh_Khan    schedule 06.02.2019
comment
Спасибо, так что бы это исправить? - person Kenny Ho; 06.02.2019