【发布时间】:2014-06-28 01:49:31
【问题描述】:
我有一个 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。我该如何解决这个问题?
【问题讨论】:
-
您应该在
viewDidLoad中添加手势识别器。您只需要添加一次——而不是每次文本视图开始编辑时。 -
不确定我是否得到这个问题,但是在创建点击手势识别器时,点击方法被称为选择器,当您开始在文本字段中输入时会调用该选择器
-
对。这意味着如果我尝试编辑 5 个文本字段,手势识别它创建了 5 次,而它只需要创建一次,在
viewDidLoad。
标签: ios objective-c uitableview uitextfield