简体   繁体   中英

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?

I guess you could access the panGestureRecognizer of the table view (because it's a type of scroll view) and get the locationInView: from it. You can then ask the table view to convert that into an index path with indexPathForRowAtPoint: .

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)")
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM