解决方案是 添加手势的代理 重写- (BOOL)gestureRecognizer:(UIGestureRecognizer )gestureRecognizer shouldReceiveTouch:(UITouch )touch 函数
以下是代码
#import "ViewController.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView * v = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 100)];
v.backgroundColor = [UIColor redColor];
[self.view addSubview:v];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewClick:)];
tap.delegate = self;
[v addGestureRecognizer:tap];
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 280, 100)];
tableView.delegate = self;
tableView.dataSource = self;
[v addSubview:tableView];
}
-(void) viewClick:(UITapGestureRecognizer*) tap
{
NSLog(@"点击view");
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell = [UITableViewCell new];
cell.textLabel.text = @"测试";
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"点击单元格");
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
// 若为UITableViewCellContentView(即点击了tableViewCell),则不截获Touch事件
if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
return NO;
}
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end