如何从UITableView iphone获取UITableView IndexPath?

在我的iPhone应用程序中,我有一个消息屏幕。 我已经在UIViewController上添加了UITapGestureRecognizer ,并且在屏幕上还有一个UITableview 。 我想selectUITableViewCell但是我不能selectUITableView因为UITapGestureRecognizer 。 当我触摸屏幕,只调用轻拍手势动作,但UITableView委托didSelectRowAtIndexPath:不被调用。 任何人都可以请帮我在点击手势和UITableView:didSelectRowAtIndexPath: 。 提前致谢。

虽然我更喜欢Matt Meyer的build议,或者我使用自定义手势识别器的其他build议,但不涉及自定义手势识别器的另一个解决scheme是让您的手势识别器识别您是否轻敲桌面视图中的单元格,如果是,手动调用didSelectRowAtIndexPath ,例如:

 - (void)handleTap:(UITapGestureRecognizer *)sender { CGPoint location = [sender locationInView:self.view]; if (CGRectContainsPoint([self.view convertRect:self.tableView.frame fromView:self.tableView.superview], location)) { CGPoint locationInTableview = [self.tableView convertPoint:location fromView:self.view]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:locationInTableview]; if (indexPath) [self tableView:self.tableView didSelectRowAtIndexPath:indexPath]; return; } // otherwise proceed with the rest of your tap handling logic } 

这是不理想的,因为如果你对tableview做任何复杂的操作(比如在单元格编辑,自定义控件等等),你会失去这种行为,但是如果你只是想要接收didSelectRowAtIndexPath ,那么这可能会做这个工作。 其他两种方法(单独的视图或自定义手势识别器)可以让您保留完整的tableviewfunction,但是如果您只需要简单一些,而且不需要tableview内置function的其余部分,就可以工作。

您可以使用TagGesture委托:

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { if ([touch.view isDescendantOfView:yourTableView]) { return NO; } return YES; } 

希望这可以帮助。

一个更简单的方法是获得两个视图:一个视图包含您想要点按手势的视图,另一个视图包含桌面视图。 你可以将UITapGestureRecognizer附加到你想要的视图上,然后它不会阻塞你的UITableView。

假设你想要轻敲手势除了在tableview之外的任何地方工作,你可以inheritance轻敲手势识别器,创build一个识别器,将忽略包含在一个excludedViews数组中的任何子视图,防止它们产生一个成功的手势(因此传递给didSelectRowAtIndexPath或其他):

 #import <UIKit/UIGestureRecognizerSubclass.h> @interface MyTapGestureRecognizer : UITapGestureRecognizer @property (nonatomic, strong) NSMutableArray *excludedViews; @end @implementation MyTapGestureRecognizer @synthesize excludedViews = _excludedViews; - (id)initWithTarget:(id)target action:(SEL)action { self = [super initWithTarget:target action:action]; if (self) { _excludedViews = [[NSMutableArray alloc] init]; } return self; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; CGPoint location = [[touches anyObject] locationInView:self.view]; for (UIView *excludedView in self.excludedViews) { CGRect frame = [self.view convertRect:excludedView.frame fromView:excludedView.superview]; if (CGRectContainsPoint(frame, location)) self.state = UIGestureRecognizerStateFailed; } } @end 

然后,当你想使用它,只需指定你想排除什么控制:

 MyTapGestureRecognizer *tap = [[MyTapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [tap.excludedViews addObject:self.tableView]; [self.view addGestureRecognizer:tap];