简体   繁体   English

tableView滚动到最新单元格的底部-scrollToRow()问题

[英]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. 我正在制作一个聊天应用程序,并且试图将tableView滚动到最近发送的消息的底部。

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. 如果我注释掉scrollToRow方法,则该应用程序运行良好,尽管tableView显然不会滚动到最新消息的底部。

Do you know what might be causing this? 你知道是什么原因造成的吗?

Use this code after you reload tableview. 重新加载tableview后使用此代码。 Don't call it in CellForRow method 不要在CellForRow方法中调用它

 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) messageTableView.scrollToRow(at:indexPath,at:UITableViewScrollPosition.bottom,动画:true)

Instead of calling this method in cell for row, call the method after table reloaddata. 在表reloaddata之后调用该方法,而不是在行的单元格中调用此方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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