Swift-Chat Log Smooth drop down loading (multiple types of cells)

zh flag
en flag

When we design the chat interface, because the chat history may be stored on the server side, or because of memory considerations, we prefer to display only a portion of the chat at the beginning, then we need to have a way to implement the previous chats. is usually achieved by pull-down (e.g. WeChat)

We can choose to add a refresh control on the tableview to implement the drop down loading, but this method is not recommended here (the reason will be mentioned later) but no matter which method we use, when we get the new data, we need to add it to the top of the tableView. in order to meet the Logic.

Source as shown in the picture:

Due to the characteristics of the TableView, when reloading the data, it will automatically jump to the top of the newly added cell, which is the top of the green shown in the image above, which will result in a sudden jump of the entire TableView after each load.

At this point, the solution we need is to keep our contentoffSet at the same time, like reference WeChat, while adding a new Cell. The code to implement this is as follows:

let OldContentsizeHeight = ListView.Contentsize.Height

ListView.ReloadData ()

ListView.Layoutifneeded ()

let NewcontentsizeHeight = ListView.Contentsize.Height

ListView.setContentOffSet (CGPoint (x: ListView.ContentsizeHeight - OldContentSizeHeight), animated: false)

In a nutshell, the content height is recorded before reload data, and the height after the reload is over, the contentoffSet is subtracted.

In this case, we need to understand how TableView calculates content height. If it's a simple single cell, the cell's height will be the same, and the

func TableView (_ TableView: UITableView, HeightForrowat Indeexpath: Indexpath) - CGFloat {}

This delegate method, but if our cell is a variety of types, then iOS provides an estimate height for cell

func TableView (_ TableView: UITableView, EstiteDheightForrowat Indexpath: Indexpath) - CGFloat {

return UitableView.AutomaticDimension

}

By implementing both this delegate and the previous delegate, iOS will automatically help us to calculate the appropriate content height so that there will be no problem with the jump (in other words, if you don't implement this method, then the method to calculate your content height is simple cell number* [cell height])

In the above way, we can implement a fixed position pull-up refresh, returning to the previous question, why not use refresh control is recommended, because

Leave a Reply

Your email address will not be published. Required fields are marked *