UITableView - scroll to the top

前端 未结 30 3050
南方客
南方客 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 17:54

    I've encountered an issue calling trying some of the methods on an empty tableView. Here's another option for Swift 4 that handles empty tableviews.

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

    Usage:

    // from yourViewController or yourTableViewController
    tableView.scrollToTop(animated: true)//or false
    

提交回复
热议问题