简体   繁体   中英

UITableView ScrollToRow function animating weirdly

The ScrollToRow is not working as I want. The function I wrote seems to be working fine, but I want it to scroll down to last row only when its added like it happens in chat. When you get a new message, your tableview scrolls to the bottom to read new message.

However, my tableview seems to reload every time before performing scrollToLastRow function (what I mean is every time before scrolling to bottom... it first goes back to top first cell and starts scrolling to bottom from there Every time when a new cell is created).

My code is simple for the scroll:

func scrollToLastRow()
{
    let indexPath = IndexPath(row: messages.count - 1, section: 0)
    self.chat.scrollToRow(at: indexPath, at: .bottom, animated: true)
}

To check my code: here's a link to my repository ChatApplication

the ViewController's used for chat is ---> chatVC the ViewController used to make chat is -> chatCell

I have tried anything I could get all over I could find. Tried dispatch (without it the scroll function wasn't working at all)

Used the function on many different places (including viewDidAppear) Used dispatch.asyncAfter for delay..... but nothing worked.

Use tableView.insertRows(at: [IndexPath], with: UITableView.RowAnimation) for adding object to end of the tableView.

From the problem you say and looking in to your code, the animation issues are due to reloading the entire tableView after a new item is added to dataSource array, What you have to do is to use Call tableView.insertRows(at: [IndexPath], with: UITableView.RowAnimation) with the correct indexPath on your tableView and the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) will be invoked.

@Fahad, you are reloading the tableview before the scrollToLast function is getting called. Please check and please verify at your end.

Note please update your GitHub repository url in your question properly as it not clickable.

Use this function for scrolling to the bottom.

   func scrollToBottom() {
        let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
        setContentOffset(bottomOffset, animated: true)
    }

use tableview.scrollToBottom()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM