UIView添加手势 然后UITableView 添加进这个View 导致UITableView 的单元格点击事件无效

#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

解决方案是 添加手势的代理 重写- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch 函数

以下是代码



版权声明:本文为博主原创文章,未经博主允许不得转载。

文章来自:http://blog.csdn.net/fhongchan/article/details/47731571
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3