UITableViewCell中的UIGestureRecognizer

时间:2015-04-20 11:23:33

标签: objective-c uitableview uigesturerecognizer

我想将UIGestureRecognizer添加到UITableViewCell 当我在panAction:课程中致电CustomCell时,它会起作用 但我想在ViewController课程中调用该方法,在这种情况下,它将不起作用。

如何修复它以使用panAction:

- (void)viewDidLoad
{
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *nibName = @"Cell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:nibName];
    if (!cell) {
        cell = (CustomCell*)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nibName];
    }
    return cell;
}

- (void)setupGesture
{
    UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    CustomCell* cell = (CustomCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell addGestureRecognizer:panRecognizer];
}

- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint location = [sender translationInView:sender.view];    
    NSLog(@"%f", location);
    [sender setTranslation:CGPointZero inView:sender.view];
}

1 个答案:

答案 0 :(得分:2)

在上面发布的代码中,您不能致电setupGesture。这样你的手机就不会拿起手势。此外,您只需添加创建并将panRecognizer添加到tableview:cellForRowAtIndexpath:中的单元格,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *nibName = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:nibName];

    UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [cell addGestureRecognizer:panRecognizer];

    return cell;
}