在原型单元第一响应器中创建UITextField

时间:2014-01-27 21:47:01

标签: ios objective-c uitableview

我已在原型单元格中设置了禁用标记和用户交互的文本字段。

这就是我创建细胞的方式。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

..
..
..
UILongPressGestureRecognizer *longPressgesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressgesture:)];
[longPressgesture setMinimumPressDuration:2.0];
[cell.contentView addGestureRecognizer: longPressgesture];
UITextField *toDoTextField = (UITextField *)[cell.contentView viewWithTag:1];
toDoTextField.tag = indexPath.row;
return cell;
}

然后我想在长按后编辑文本字段。所以我有这个:

- (void)LongPressgesture:(UILongPressGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateEnded) {

    }

    else {
        UITableView* tableView = (UITableView*)self.view;
        CGPoint touchPoint = [recognizer locationInView:self.view];
        NSIndexPath* row = [tableView indexPathForRowAtPoint:touchPoint];
        NSInteger rowRow = [row row];
        UITextField *toDoTextField = (UITextField *)[cell.contentView viewWithTag:rowRow];    
        toDoTextField.userInteractionEnabled = YES;
        [toDoTextField becomeFirstResponder];
}

当我触发长按时虽然只有最后一个单元格可以工作。不知道我做错了什么。

我希望能够长按任何单元格,然后编辑文本。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

将长按手势识别器添加到表格视图而不是单元格

UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] 
  initWithTarget:self action:@selector(handleLongPress:)];
recognizer.minimumPressDuration = 2.0;
[self.myTableView addGestureRecognizer:recognizer];

然后像这样处理:

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{

    if (recognizer.state != UIGestureRecognizerStateEnded)
      return;

    CGPoint p = [gestureRecognizer locationInView:self.myTableView];

    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
    if (!indexPath)
        NSLog(@"Long press was on tableView, but not on a row");
    else
    {
        NSLog(@"Long press on table view @ row %d", indexPath.row);
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        NSAssert(cell, @"Cell must be found");
        if (!cell)
           return;

        UITextField *toDoTextField = 
                     (UITextField *)[cell.contentView viewWithTag:indexPath.row];    

        NSAssert(toDoTextField, @"UITextField must be found by tag");
        if (toDoTextField)
        {
           [self.tableView endEditing:YES];
           toDoTextField.userInteractionEnabled = YES;
           [toDoTextField becomeFirstResponder];
        }
    }
}