Вставьте и удалите строки для эффекта «Развернуть и свернуть» для табличного представления - PullRequest
0 голосов
/ 06 февраля 2019

У меня проблема с источником данных.причина: 'попытка вставить строку 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
}

1 Ответ

0 голосов
/ 06 февраля 2019

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

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

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

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

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


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"]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...