UITableView - scroll to the top

前端 未结 30 2979
南方客
南方客 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 17:56

    Possible Actions:

    1

    func scrollToFirstRow() {
        let indexPath = NSIndexPath(forRow: 0, inSection: 0)
        self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
    }
    

    2

    func scrollToLastRow() {
        let indexPath = NSIndexPath(forRow: objects.count - 1, inSection: 0)
        self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
    }
    

    3

    func scrollToSelectedRow() {
        let selectedRows = self.tableView.indexPathsForSelectedRows
        if let selectedRow = selectedRows?[0] as? NSIndexPath {
            self.tableView.scrollToRowAtIndexPath(selectedRow, atScrollPosition: .Middle, animated: true)
        }
    }
    

    4

    func scrollToHeader() {
        self.tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
    }
    

    5

    func scrollToTop(){
        self.tableView.setContentOffset(CGPointMake(0,  UIApplication.sharedApplication().statusBarFrame.height ), animated: true)
    }
    

    Disable Scroll To Top:

    func disableScrollsToTopPropertyOnAllSubviewsOf(view: UIView) {
        for subview in view.subviews {
            if let scrollView = subview as? UIScrollView {
                (scrollView as UIScrollView).scrollsToTop = false
            }
            self.disableScrollsToTopPropertyOnAllSubviewsOf(subview as UIView)
        }
    }
    

    Modify and use it as per requirement.

    Swift 4

      func scrollToFirstRow() {
        let indexPath = IndexPath(row: 0, section: 0)
        self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
      }
    

提交回复
热议问题