Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indexPath of "next" UITableViewCell

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?

like image 874
borchero Avatar asked Dec 14 '14 17:12

borchero


People also ask

How do I get the indexPath of a cell Swift?

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.

What does indexPath row return?

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.

What is indexPath in tableView Swift?

indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.


1 Answers

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

like image 112
Bart van Kuik Avatar answered Oct 04 '22 00:10

Bart van Kuik