When I touch (Touch Up) a UITableViewCell my ViewController's UITableViewDelegate method - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath is called. I need to get the x-coordinate of the Touch-Point at this time as well so that I can know what portion of the Cell was touched (non-accessory items). I have tried using the usual touch methods such as TouchesDidEnd but the coordinates always return x=0.000 y=0.000 no matter where I touched (A location in a custom UITableViewCell in a UITableView object in my ViewController). I also tried implementing touch handling from within the Custom Cell class and while I COULD get accurate coordinates alas I could find no way to communicate those coordinates to my ViewController class (which has the UITableView).
Q: Is there a good way I can get the x-coordinates of the device's screen when I touch a custom UITableViewCell?
Put a transparent UIView
atop your table view, override its -touchesBegan:withEvent:
etc. methods. In those overridden methods, get the UITouch
objects and call -locationInView:
on them to get the CGPoint
values.
That gives you the coordinates of a touch event.
Then you just pass on those UITouch
events to the underlying table view. The table view handles its usual business of passing touches on to rows, etc.
1. Add a tapGestureRecognizer to your tableView
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tableViewTapped(recognizer:)))
tableView.addGestureRecognizer(tapGestureRecognizer)
2. Write a function to handle the tapGesture
@objc func tableViewTapped(recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: self.tableView) // point of touch in tableView
if let indexPath = self.tableView.indexPathForRow(at: location) { // indexPath of touch location
if let cell = tableView.cellForRow(at: indexPath) as? MyCustomCell {
let locationInCell = recognizer.location(in: cell) // point of touch in cell
// do something with location or locationInCell
if cell.imageView.frame.contains(location) || cell.imageView.frame.contains(locationInCell) {
print("ImageView inside cell tapped!")
}
}
}
}
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