How to scroll to the exact end of the UITableView?

前端 未结 16 2562
天涯浪人
天涯浪人 2020-12-07 18:48

I have a UITableView that is populated with cells with dynamic height. I would like the table to scroll to the bottom when the view controller is pushed from vi

16条回答
  •  鱼传尺愫
    2020-12-07 19:16

    I would use more generic approach to this:

    Swift4

    extension UITableView {
    
        func scrollToBottom(){
    
            DispatchQueue.main.async {
                let indexPath = IndexPath(
                    row: self.numberOfRows(inSection:  self.numberOfSections-1) - 1, 
                    section: self.numberOfSections - 1)
                if hasRowAtIndexPath(indexPath) {
                    self.scrollToRow(at: indexPath, at: .bottom, animated: true)
                }
            }
        }
    
        func scrollToTop() {
    
            DispatchQueue.main.async {
                let indexPath = IndexPath(row: 0, section: 0)
                if hasRowAtIndexPath(indexPath) {
                    self.scrollToRow(at: indexPath, at: .top, animated: false)
               }
            }
        }
    
        func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
            return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRows(inSection: indexPath.section)
        }
    }
    

提交回复
热议问题