I have some code when tapping on a cell of a table view. Under certain circumstances I want to call the function tableView(_, didSelectRowAtIndexPath)
recursively for the next cell. That means that when I selected row 5, I want to select row 6, etc.
How can I get the indexPath of the next cell based on another row?
The sender argument is the button object. You can walk up the view hierarchy to find the containing table view cell and the containing table view. Then you can ask the table view for the cell's index path.
So to start with the indexPath. row will be 0. Then it will be 1, then 2, then 3 and so on. You do this so that you can get the correct string from the array each time.
indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.
Here's an answer in Swift:
private func nextIndexPath(for currentIndexPath: IndexPath, in tableView: UITableView) -> IndexPath? {
var nextRow = 0
var nextSection = 0
var iteration = 0
var startRow = currentIndexPath.row
for section in currentIndexPath.section ..< tableView.numberOfSections {
nextSection = section
for row in startRow ..< tableView.numberOfRows(inSection: section) {
nextRow = row
iteration += 1
if iteration == 2 {
let nextIndexPath = IndexPath(row: nextRow, section: nextSection)
return nextIndexPath
}
}
startRow = 0
}
return nil
}
I use this code because I have a tableview with custom cells that contain a UITextField
. It's configured with a Next button, and when that button is tapped, the focus is moved to the next UITextField
.
To go to the previous indexPath, see this answer: https://stackoverflow.com/a/56867271/
For an example project that includes a previous/next button as a toolbar above a keyboard, check out the example project: https://github.com/bvankuik/TableViewWithTextFieldNextButton
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With