Swifty
Swifty

Reputation: 905

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?

Upvotes: 0

Views: 279

Answers (2)

Pavan Kumar
Pavan Kumar

Reputation: 11

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)

Upvotes: 1

Manish Mahajan
Manish Mahajan

Reputation: 2092

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)

Upvotes: 1

Related Questions