简体   繁体   中英

tableView scrolling to the bottom of the most recent cell - issue with scrollToRow()

I am making a chat app and I am trying to make the tableView scroll to the bottom of the most recently sent message.

Below is a code snippet of my protocol methods:

extension ChatViewController: UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return messages.count
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! MessageCell
    cell.message.text = messages[indexPath.row].messageContent
    cell.userName.text = messages[indexPath.row].sender

    // The method below causes an error that crashes the app at runtime
    messageTableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true)

The last line causes the following error:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee29d4ff8

which seems to indicate some sort of overflow caused by an infinite loop (since the messages don't even load on the screen). If I comment out the scrollToRow method, the app runs fine, although the tableView obviously does not scroll to the bottom of the latest message.

Do you know what might be causing this?

Use this code after you reload tableview. Don't call it in CellForRow method

 let indexPath = IndexPath(row: messages.count - 1, section: 0);
 yourTableView.scrollToRow(at: indexPath, at: .top, animated: false)

Don't Place below code in cell for row, because cell for row will call for every time when cell loads. so thats way it creates the problem for you (crashes the app at runtime).

messageTableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true)

Instead of calling this method in cell for row, call the method after table reloaddata.

let indexPath = IndexPath(row: messages.count - 1, section: 0); yourTableView.scrollToRow(at: indexPath, at: .top, animated: false)

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