Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i automatically scroll in a table view? (Swift)

Tags:

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)
like image 944
nachshon f Avatar asked Mar 31 '15 20:03

nachshon f


1 Answers

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)
like image 111
Victor Sigler Avatar answered Sep 21 '22 07:09

Victor Sigler