быстро сохранить положение данных таблицы после перезагрузки - PullRequest
1 голос
/ 24 марта 2019

добавьте новые данные в tableview, когда прокрутка превышает 50% содержимого, но проблема в том, что после добавления прокрутки перемещается содержимое вверх, как я могу сохранить местоположение и прокрутку?изменил отображаемое содержимое таблицы, которое начиналось бы снизу

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if (self.lastContentOffset > scrollView.contentOffset.y && loadEarlierShowF) {
        let height = scrollView.frame.size.height
        let cHeight = scrollView.contentSize.height
        let contentYoffset = scrollView.contentOffset.y
        let distanceFromBottom = scrollView.contentSize.height - contentYoffset
        print(distanceFromBottom)
        let eght = cHeight / 100 * 50
        if distanceFromBottom >= eght {

            actionLoadEarlier()

        }
    }
}

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

    if (indexPath.row == 0) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RCSectionHeaderCell", for: indexPath) as! RCSectionHeaderCell
        cell.bindData(indexPath, messagesView: self)
        return cell
    }

    if (indexPath.row == 1) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RCBubbleHeaderCell", for: indexPath) as! RCBubbleHeaderCell
        cell.bindData(indexPath, messagesView: self)
        return cell
    }

    if (indexPath.row == 2) {
        let rcmessage = self.rcmessage(indexPath)
        if (rcmessage.type == RC_TYPE_STATUS) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "RCStatusCell", for: indexPath) as! RCStatusCell
            cell.bindData(indexPath, messagesView: self)
            return cell
        }
        if (rcmessage.type == RC_TYPE_TEXT) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "RCTextMessageCell", for: indexPath) as! RCTextMessageCell
            cell.bindData(indexPath, messagesView: self)
            let numSections = self.tableView.numberOfSections
            if numSections == 1  {
                updateTableContentInset()
            }
            return cell
        }

    }

    if (indexPath.row == 3) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RCBubbleFooterCell", for: indexPath) as! RCBubbleFooterCell
        cell.bindData(indexPath, messagesView: self)
        return cell
    }

    if (indexPath.row == 4) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RCSectionFooterCell", for: indexPath) as! RCSectionFooterCell
        cell.bindData(indexPath, messagesView: self)
        return cell
    }

    return UITableViewCell()
}
func updateTableContentInset() {
    let numSections = self.tableView.numberOfSections

    var contentInsetTop = self.tableView.bounds.size.height

    for section in 0..<numSections {
        let numRows = self.tableView.numberOfRows(inSection: section)
        let sectionHeaderHeight = self.tableView.rectForHeader(inSection: section).size.height
        let sectionFooterHeight = self.tableView.rectForFooter(inSection: section).size.height
        contentInsetTop -= sectionHeaderHeight + sectionFooterHeight
        for i in 0..<numRows {
            let rowHeight = self.tableView.rectForRow(at: IndexPath(item: i, section: section)).size.height
            contentInsetTop -= rowHeight
            if contentInsetTop <= 0 {
                contentInsetTop = 0
                break
            }
        }

        if contentInsetTop == 0 {
            break
        }
    }
    self.scrollView.contentInsetAdjustmentBehavior = .never
    self.tableView.contentInsetAdjustmentBehavior = .never
    self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0)

}

как это сделать, добавив новые данные, и содержимое данных прокрутки осталось на месте (в примере телеграмма)

Пробовал так, но смещается не туда

let offset = tableView.contentOffset    
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.setContentOffset(offset, animated: false)
....
let indexPath = IndexPath(row: 2, section: tableView.numberOfSections - 1)
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.scrollToRow(at: indexPath, at: .top, animated: false)

1 Ответ

0 голосов
/ 24 марта 2019

Почему вы можете попробовать это?

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableTest.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = arrayTemp[indexPath.row]

    if indexPath.row > (arrayTemp.count / 2) {
        callNewData()
    }
    return cell
}

Вы можете использовать индекс, загруженный в таблицу, чтобы добавить больше значений.

при загрузке ячейки вы можете вызвать функцию, чтобы добавить больше данных в табличное представление, так что если данныеНачав с 10 значений, когда загружается 5 ячеек, вы добавляете еще 10 itens в массив temp, так что теперь массив имеет 20 значений, когда таблица загружает индекс 10, вы вызываете больше itens.

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