UITableView - scroll to the top

前端 未结 30 2966
南方客
南方客 2020-11-28 17:22

In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section

30条回答
  •  攒了一身酷
    2020-11-28 18:03

    In Swift 5 , Thanks @Adrian's answer a lot

    extension UITableView{
    
        func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
            return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section)
        }
    
        func scrollToTop(_ animated: Bool = false) {
            let indexPath = IndexPath(row: 0, section: 0)
            if hasRowAtIndexPath(indexPath: indexPath) {
                scrollToRow(at: indexPath, at: .top, animated: animated)
            }
        }
    
    }
    

    Usage:

    tableView.scrollToTop()
    

提交回复
热议问题