我正在制作聊天应用,我正在尝试将tableView滚动到最近发送的消息的底部。
以下是我的协议方法的代码片段:
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)
最后一行导致以下错误:
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee29d4ff8
这似乎表明由无限循环引起的某种溢出(因为消息甚至不会在屏幕上加载)。如果我注释掉scrollToRow
方法,应用程序运行正常,尽管tableView显然不会滚动到最新消息的底部。
你知道造成这种情况的原因吗?
答案 0 :(得分:2)
重新加载tableview后使用此代码。不要在CellForRow方法中调用它
let indexPath = IndexPath(row: messages.count - 1, section: 0);
yourTableView.scrollToRow(at: indexPath, at: .top, animated: false)
答案 1 :(得分:1)
不要将 代码放在行的单元格中,因为每次单元格加载时,行的单元格都会调用。这就是它为你创造问题的方法(在运行时崩溃应用程序)。
messageTableView.scrollToRow(at:indexPath,at:UITableViewScrollPosition.bottom,animated:true)
不是在单元格中为行调用此方法,而是在table reloaddata之后调用该方法。
让indexPath = IndexPath(row:messages.count - 1,section:0); yourTableView.scrollToRow(at:indexPath,at:。top,animated:false)