Wayne Filkins Wayne Filkins - 1 year ago 61
iOS Question

How can I use hitTest to get underlying views if they are in a table?

This code help me get the views beneath the main view:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

let location = touches.first!.locationInView(self.view)

let view = self.view.hitTest(location, withEvent: event)

print("View: %@", NSStringFromClass((view?.classForCoder)!))

Is there some way to do this for a table? I have a table with cells and I want to see which cell the user is dragging over, or which view within the cell. My goal is to use a button to disable scroll, then be able to drag over the table and print out the cell or view within the cell as the user drags over them.

Answer Source

You can query the UITableView for the index-path based on cell subviews.

let point = cellSubView.convertPoint(cellSubView.bounds.origin, toView: tableView)
let index = tableView.indexPathForRowAtPoint(point)

indexPathForRowAtPoint() returns nil if point is outside of any row in the table

EDIT: to handle the touches on the tableView you have to set a gesture recognizer on it.

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapOnTableView(_:)))

func didTapOnTableView(gesture: UITapGestureRecognizer){
    let touchPoint = gesture.locationInView(tableView)
    let index = tableView.indexPathForRowAtPoint(touchPoint)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download