Auto scrolling to a cell with a specific value
Swift 3.0
let indexPath = NSIndexPath(forRow: 5, inSection: 0)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
Swift 4.0
let lastRowIndex = self.tblRequestStatus!.numberOfRows(inSection: 0) - 1
let pathToLastRow = IndexPath.init(row: lastRowIndex, section: 0)
tableView.scrollToRow(at: pathToLastRow, at: .none, animated: false)
You can use find the index of the item(which will be its row), and then scroll to that index. find
function returns the index of a particular element in the array.
if let index = find(items, groupNoToScroll)
{
let indexPath = NSIndexPath(forRow: index, inSection: 0)
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
}
Do this to find the first element in the array that is equal to groupNoToScroll. Then, go to that row.
var rowToGoTo:Int = 0 //Rather use the Swift find function.
for x in items{
if x == groupNoToScroll{
break
}
rowToGoTo++
}
let lastRow = tableView.indexPathsForVisibleRows()?.last as NSIndexPath
if indexPath.row == lastRow.row {
if scrollToTime == true {
let indexPath = NSIndexPath(row: rowToGoTo, section: 0)
tblBusList.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
}
}
But I would recommend doing this in viewDidAppear.
As Isuru pointed out rather use the find function.
Swift 4:
let indexPath = IndexPath(row: row, section: section)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
(first, of course, you have to assign values to row and section based on which cell you want to scroll to)