Mian Ahmad
Mian Ahmad

Reputation: 11

How to scroll to the bottom cell of tableview in swift 5

I have created a chat view in which I have used tableview, the basic feature of ChatView is to show the latest messages(last cell), But tableView is not scrolling to last index, it's always stuck somewhere in the middle

 func scrollToBottom()  {
    let point = CGPoint(x: 0, y: self.chatTableView.contentSize.height + 200.0)
            self.chatTableView.setContentOffset(point, animated: true)
    }

Upvotes: 1

Views: 1369

Answers (2)

s.Aulakh
s.Aulakh

Reputation: 165

Swift 5

Hi,you just have to call this line of code after loading table view.

  self. chatTableView.scrollToRow(at: IndexPath(row: lastRowIndex, section: 0), at: .bottom, animated: true)

(In place of "lastRowIndex", you have to enter index of your last row of tableView. You can use the value of count of your Array that you are using to populate tableView. For example: (yourArray.count - 1))

Upvotes: 2

stonemover
stonemover

Reputation: 1

override func viewDidLoad() {
    super.viewDidLoad()
    
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
        self.scrollToBottom()
    }
}
private func scrollToBottom(){
    let y = self.collectionView.contentSize.height - self.collectionView.btHeight() + self.collectionView.adjustedContentInset.bottom
    self.collectionView.setContentOffset(CGPoint.init(x: 0, y: y), animated: false)
    if self.loadingView.superview != nil {
        self.loadingView.removeFromSuperview()
    }
    
}

Upvotes: 0

Related Questions