UITableView - scroll to the top

前端 未结 30 2735
南方客
南方客 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:00

    Swift:

    tableView.setContentOffset(CGPointZero, animated: true)
    
    0 讨论(0)
  • 2020-11-28 18:00

    Swift 3

    tableView.setContentOffset(CGPoint.zero, animated: true)
    

    if tableView.setContentOffset don't work.

    Use:

    tableView.beginUpdates()
    tableView.setContentOffset(CGPoint.zero, animated: true)
    tableView.endUpdates()
    
    0 讨论(0)
  • 2020-11-28 18:00

    in swift

    your row = selectioncellRowNumber your section if you have = selectionNumber if you dont have set is to zero

    //UITableViewScrollPosition.Middle or Bottom or Top

    var lastIndex = NSIndexPath(forRow:  selectioncellRowNumber, inSection: selectionNumber)
    self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
    
    0 讨论(0)
  • 2020-11-28 18:03

    Swift 4:

    This works very well:

    //self.tableView.reloadData() if you want to use this line remember to put it before 
    let indexPath = IndexPath(row: 0, section: 0)
    self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    
    0 讨论(0)
  • 2020-11-28 18:03

    Here's what I use to work correctly on iOS 11:

    extension UIScrollView {
        func scrollToTop(animated: Bool) {
            var offset = contentOffset
            if #available(iOS 11, *) {
                offset.y = -adjustedContentInset.top
            } else {
                offset.y = -contentInset.top
            }
            setContentOffset(offset, animated: animated)
        }
    }
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题