Scroll all the way down to the bottom of UITableView

后端 未结 1 1170
难免孤独
难免孤独 2021-01-05 13:09

I\'ve a UITableView and I\'m trying to load 36 rows into it and then scroll all the way down the last cell.

I\'ve tried this:

func rel         


        
1条回答
  •  鱼传尺愫
    2021-01-05 13:41

    If your requirement is to scroll to the last cell of tableView you can use setContentOffset like this so that you can scroll to the last cell of tableView.

    let scrollPoint = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.frame.size.height)
    self.tableView.setContentOffset(scrollPoint, animated: true)
    



    It was a combination of answers. I ended up doing this:

    Put this in the reloadData() function:

    func reloadData(){
        chatroomTableView.reloadData()
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let scrollPoint = CGPoint(x: 0, y: self.chatroomTableView.contentSize.height - self.chatroomTableView.frame.size.height)
            self.chatroomTableView.setContentOffset(scrollPoint, animated: true)
        })
    }
    

    Added this to my UITableViewDelegate :

    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
            let lastRowIndex = tableView.numberOfRowsInSection(0)
            if indexPath.row == lastRowIndex - 1 {
                tableView.scrollToBottom(true)
            }
        }
    

    Added this to the bottom of my .swift file:

    extension UITableView {
        func scrollToBottom(animated: Bool = true) {
            let sections = self.numberOfSections
            let rows = self.numberOfRowsInSection(sections - 1)
            if (rows > 0){
                self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true)
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题