我有一个UITableView,我已经为每个单元格分配了一个UITextField . 我希望能够接受来自每个文本字段的输入,并在用户点击屏幕上除键盘之外的任何位置时关闭键盘 . 这是我到目前为止的代码,但是当我在表格的最后一个单元格中时,我发现键盘只会被解雇 .
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self.gradesTableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
self.tf = [[UITextField alloc] initWithFrame:CGRectMake(225, (cell.contentView.bounds.size.height-30)/2, 50, 30)];
[self.tf setDelegate: self];
self.tf.tag = indexPath.row;
self.tf.textAlignment = NSTextAlignmentCenter;
self.tf.placeholder = @"0";
self.tf.backgroundColor = [UIColor grayColor];
self.tf.borderStyle = UITextBorderStyleRoundedRect;
self.tf.keyboardType = UIKeyboardTypeDecimalPad;
[cell addSubview:self.tf];
cell.textLabel.text = [self.adderArrayLabels objectAtIndex:indexPath.section];
return cell;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
self.tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
[self.view addGestureRecognizer:self.tapGR];
NSLog(@"Started editing");
}
我已经尝试了 endEditing:
和 resignFirstResponder
,但是当我在最后一个单元格的文本字段上时,它们都只关闭了键盘 .
- (void)tap {
[self.tf endEditing:YES];
//[self.tf resignFirstResponder];
NSLog(@"tap called");
self.tapGR.enabled = NO;
}
使用代码中的NSLog语句,我可以确认每次识别出适当的敲击手势但仍然键盘停留时调用方法 tap
. 我该如何解决?
1 回答
问题出在这里:
您的类具有文本字段属性,每次创建新文本字段时,都将其分配给此属性 . 然后,您只在此属性上尝试
endEditing:
或resignFirstResponder
,该属性始终是最近创建的单元格上的文本字段 .您根本不需要此属性,只能在创建单元格时使用本地文本字段变量 .
然后将点击方法更改为:
确实,该方法应该是:
- (void)tap:(id)sender;
另外,正如我评论的那样,手势识别器应该添加到
viewDidLoad
中 . 我们只需要添加一次,而不是每次文本字段开始编辑时 . 每次文本字段开始编辑时添加它的唯一原因是,如果您每次文本字段结束编辑时也删除它...但是作为手势调用的方法只是摆脱键盘,我认为没有理由要做到这一点 .