Josh O'Connor Josh O'Connor - 5 months ago 6
iOS Question

Obtain the indexPath of UITableView's cell when scrolling

When you scroll in a tableview, it doesnt begin the table delegate method didSelectRowAtIndexPath method over the cell that your finger is on. If I were to tap that call, instead of slide it up/down, it grants me the indexPath with the delegate method.

I was wondering if I could obtain the indexPath of the cell that my finger is on when scrolling the tableView. Is this possible?

Answer

this could be the way to go:

class TableViewController: UITableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell")
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
        }

        cell.textLabel?.text = "\(indexPath.row)"

        return cell
    }

    override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        let location = scrollView.panGestureRecognizer.locationInView(tableView)
        guard let indexPath = tableView.indexPathForRowAtPoint(location) else {
            print("could not specify an indexpath")
            return
        }

        print("will begin dragging at row \(indexPath.row)")
    }

}
Comments