我想将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];
}
答案 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;
}