【问题标题】:tableView scrolling to the bottom of the most recent cell - issue with scrollToRow()tableView 滚动到最新单元格的底部 - scrollToRow() 的问题
【发布时间】:2023-03-28 04:26:01
【问题描述】:

我正在制作一个聊天应用程序,我正在尝试让 tableView 滚动到最近发送的消息的底部。

下面是我的协议方法的代码sn-p:

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 显然不会滚动到最新消息的底部。

你知道是什么原因造成的吗?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    在重新加载 tableview 后使用此代码。不要在 CellForRow 方法中调用它

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

    【讨论】:

    • 我已将此代码放入用于从数据库中检索消息的方法中,并且它有效。我会接受您的回答,但首先您能否向我解释我做错了什么以及为什么这会起作用?顺便谢谢你的帮助!!
    • 首先您需要检查 CellForRow 方法的工作原理。获得所有数据后,scrollToRow 将起作用。
    【解决方案2】:

    不要将 below 代码放在单元格中,因为每次加载单元格时都会调用单元格。所以这就是它为您制造问题的方式(在运行时使应用程序崩溃)。

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

    不要在单元格中为行调用此方法,而是在表重新加载数据之后调用该方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多