2017-05-17 65 views
1

我正在開發iOS聊天應用程序,並且在聊天視圖中遇到問題。我在聊天視圖中使用UITableViewController。有時我的桌子在插入新行時會跳轉,如您在視頻中所看到的:https://youtu.be/8IgEUJ5uYAciOS UITableViewController - 插入並滾動到底部 - 有時會跳躍

這是我如何插入和滾動到表的底部:

 self.conversation.append(message) 

     self.tableView.beginUpdates() 
     self.tableView.insertRows(at: [IndexPath(row: self.conversation.count - 1, section: 0)], with: UITableViewRowAnimation.none) 
     self.tableView.endUpdates() 


     DispatchQueue.main.async { 
      self.tableView.scrollToRow(at: IndexPath(row: self.conversation.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: false) 
      self.footerView?.isHidden = true 
      self.theMessage.text = nil 
      self.switchBottomActions(showSend: false) 
     } 

每個報文對象有一個名爲estimatedMessageHeight屬性。我在那裏保存消息單元大小,所以tableView的heightForRowAt代碼是:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 

    guard let cellHeight = self.conversation[indexPath.row].estimatedHeight else { 

     return 0 

    } 

    return cellHeight 

} 

任何解決方案?

+0

取消選擇故事板中的反彈選項。 –

+0

@Robert Constantinescu,你找到解決方案嗎?你可以請張貼正確的答案。我也想插入和動畫底部行像WhatsApp。 –

回答

0

你應該取消選中反彈垂直在屬性檢查器爲您的UITableView。 enter image description here

+0

不,它沒有幫助我。 –

2

我也面臨同樣的問題,最後我最終以下面的解決方案。它給了我像在WhatsApp應用程序中一樣的動畫感受。

UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { 

     let reloadIndexPath = IndexPath(item: self.arrTableVwData.count - 1, section: 0) 

     self.tableVw.beginUpdates() 
     self.tableVw.insertRows(at:[reloadIndexPath], with: UITableViewRowAnimation.fade) 
     self.tableVw.endUpdates() 
     self.tableVw.scrollToRow(at: reloadIndexPath, at: .bottom, animated: false) 

    }, completion: nil) 

注:請不要通過任何類型的動畫在options:[]因爲我們已經將它們在insertRowsscrollToRow方法。

0

使該功能:

func scrollToBottom(){ 
    DispatchQueue.main.async { 
     let indexPath = IndexPath(row: self.chatListDB.count-1, section: 0) 
     self.tblView.scrollToRow(at: indexPath, at: .bottom, animated: false) 
    } 
} 

並插入值後調用它。