20

I added a search bar to my table view, and as the user searches, I want the table view to scroll to the text that your typed.

How do I make the scroll view scroll automatically?

This is what I tried, but I get an error saying that an Integer is not convertible to an index Path. What should I do?

self.tableview.scrollToRowAtIndexPath(1, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

or

self.tableview.scrollToNearestSelectedRowAtScrollPosition(scrollPosition: UITableViewScrollPosition.Middle, animated: true)

7 Answers 7

31

You have to call the method scrollToRowAtIndexPath in the following way :

var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath, 
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

The above example assume you have only one section. I hope this help you.

For Swift 3:

let indexPath = NSIndexPath(item: numberOfRowYouWant, section: 2)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.middle, animated: true)

For Swift 4:

let indexPath = NSIndexPath(item: numberOfRowYouWant, section: 2)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableView.ScrollPosition.middle, animated: true)
1
  • 1
    when you havent a search bar, just a normal table: call it in viewDidAppear() and you have a nice animation, viewDidload worked for me too, but without animation
    – kuzdu
    Apr 26, 2016 at 13:57
12

For Swift 5 ( Xcode 11.2.1 ):

    let numberOfSections = self.tableView.numberOfSections
    let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

    let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
    self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)

For Swift 2:

    let numberOfSections = self.tableView.numberOfSections
    let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

    let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
    self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)
5

If you want scroll down automatically:

numberOfSections = tableView.numberOfSections()
let numberOfRows = tableView.numberOfRowsInSection(numberOfSections-1)

var indexPath = NSIndexPath(forRow: numberOfRows, inSection: numberOfSections)
self.tableview.scrollToRowAtIndexPath(indexPath, 
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

Swift 4:

let numberOfSections = tableView.numberOfSections
let numberOfRows = tableView.numberOfRows(inSection: numberOfSections - 1)

let indexPath = NSIndexPath(row: numberOfRows, section: numberOfSections)
self.tableView.scrollToRow(at: indexPath as IndexPath,
                                  at: UITableView.ScrollPosition.middle, animated: true)
3
  • Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long, but it is expected.
    – peterh
    Sep 8, 2015 at 18:12
  • Thanks for sharing the code! I referenced it to create an updated version for Swift 2.0.
    – xke
    Nov 3, 2015 at 7:46
  • Thanks, it help me very much!
    – javimuu
    Feb 14, 2017 at 9:46
3

Here's the Swift 2.0 version to scroll to the last row of multiple sections, based on the code from Thiago earlier in this thread:

let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections-1)

print ("scrolling to bottom row \(numberOfRows)")

let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: numberOfSections-1)
self.tableView.scrollToRowAtIndexPath(indexPath,
                        atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
0

SWIFT 4

/* Variables */
  var scrollTimer = Timer()


//  AN AUTOMATIC SCROLL OF THE YOUT IMAGE
scrollTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(automaticScroll), userInfo: nil, repeats: true)




// MARK: - SCROLLVIEW DELEGATE: SHOW CURRENT PAGE IN THE PAGE CONTROL
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let pageWidth = containerScrollView.frame.size.width
    let page = Int(floor((containerScrollView.contentOffset.x * 2 + pageWidth) / (pageWidth * 2)))
    pageControl.currentPage = page

}

// MARK: - AUTOMATIC SCROLL
@objc func automaticScroll() {
    var scroll = containerScrollView.contentOffset.x
    if scroll < CGFloat(view.frame.size.width) * CGFloat(numberOfImages-1) {
        scroll += CGFloat(view.frame.size.width)
        containerScrollView.setContentOffset(CGPoint(x: scroll, y:0), animated: true)
    } else {
        // Stop the timer
        scrollTimer.invalidate()
    }
}
1
  • Looks like you posted answer for UICollection view not for UITableView as UITableView can't scroll to horizontal. Jul 11, 2019 at 7:28
0

> To start scrolling:

private var autoTimer = Timer()

private func startAutoScroll(duration: TimeInterval, direction: ScrollDirectionType) {
        var currentOffsetY = tableView.contentOffset.y
        var shouldFinish = false
        autoTimer = Timer.scheduledTimer(withTimeInterval: duration, repeats: true, block: { [weak self] (_) in
            guard let self = self else { return }
            switch direction {
            case .top:
                currentOffsetY = (currentOffsetY - 10 < 0) ? 0 : currentOffsetY - 10
                shouldFinish = currentOffsetY == 0
            case .bottom:
                let highLimit = self.tableView.contentSize.height - self.tableView.bounds.size.height
                currentOffsetY = (currentOffsetY + 10 > highLimit) ? highLimit : currentOffsetY + 10
                shouldFinish = currentOffsetY == highLimit
            default: break
            }
            DispatchQueue.main.async {
                UIView.animate(withDuration: duration * 2, animations: {
                    self.tableView.setContentOffset(CGPoint(x: 0, y: currentOffsetY), animated: false)
                }, completion: { _ in
                    if shouldFinish { self.stopScrolling() }
                })
            }
        })
    }

> To End Scrolling

 private func stopScrolling() {
    if autoTimer.isValid {
        view.layer.removeAllAnimations()
        autoTimer.invalidate()
    }
}
-1

Swift 4:

let indexPath = IndexPath(row: numberOfRowYouWant, section: 0) 

self.verbsTable.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.