UITableView Refresh without scrolling

后端 未结 12 568
时光说笑
时光说笑 2021-02-03 23:06

I have a _TableView with items , and I want to set automatic refresh,and I don\'t want it to scroll on refresh , lets say user scrolled 2 pages down , and the refre

12条回答
  •  鱼传尺愫
    2021-02-03 23:40

    I'm doing it this way:

    messages.insertContentsOf(incomingMsgs.reverse(), at: 0)
    table.reloadData()
    
    // This is for the first load, first 20 messages, scroll to bottom
    if (messages.count <= 20) {
          let indexToScroll = NSIndexPath(forRow: saferSelf.messages.count - 1, inSection: 0)
          table.scrollToRowAtIndexPath(indexToScroll, atScrollPosition: .Top , animated: false)
    }
    // This is to reload older messages on top of tableview
    else {
          let indexToScroll = NSIndexPath(forRow: incomingMsgs.count, inSection: 0)
          table.scrollToRowAtIndexPath(indexToScroll, atScrollPosition: .Top , animated: false)
          // Remove the refreshControl.height + tableHeader.height from the offset so the content remain where it was before reload
          let theRightOffset = CGPointMake(0, table.contentOffset.y - refreshControl.frame.height - table.headeView.frame.height)
          table.setContentOffset(theRightOffset, animated: false)
    }
    

    ...also, since I use dynamic cell height, to avoid some weirdness, the estimation is cached:

    var heightAtIndexPath = [NSIndexPath: CGFloat]()
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return heightAtIndexPath[indexPath] ?? UITableViewAutomaticDimension
    }
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        heightAtIndexPath[indexPath] = cell.frame.height
    }
    

提交回复
热议问题