当我在UITextField上点击并转到UITableView时,如何使resignFirstResponder生效?

6

我在我的iPhone应用程序中遇到了一个问题,由于我有一个UITableView占据了屏幕的其余空间,所以即使将UIView设置为控制器,它也是不可触摸的。

我想知道如何通过点击UITableView来重新设置键盘,也就是firstResponder?是否有一种方法可以监视UITableView上的触摸事件,即使不是选择可点击单元格的方式。

基本上,如果单元格触发事件,我知道如何取消键盘,但是,如果我单击UITableView的不可点击部分,我仍希望键盘消失。

4个回答

6

两种选择:

  • 在您的视图控制器中,响应表格的滚动回调并取消响应者
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     [self.view endEditing:YES];
}
  • 您可以随时向表格/视图添加UITapGestureRecognizer,并从那里取消响应者

个人而言,我通常在表格滚动时这样做,因为我不喜欢单击即可关闭键盘。


谢谢,UITapGestureRecognizer正好做到了我需要的功能。感谢您的时间。我相信滚动也可以实现,但在这种情况下我只需要点击,但是我会将滚动保留在我的库存中以备将来使用。 - Rob

4

添加轻拍手势识别器是一个有趣的解决方案,但是还有一种选择,您不需要编写任何代码!

您可以在Interface Builder中设置属性keyboardDismissMode为“Dismiss on drag”,使其适用于您的表视图。它是从UIScrollView继承的属性,每当您滚动表视图时,键盘就会被取消。


3
   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    UITapGestureRecognizer *doubleTap = 
            [[UITapGestureRecognizer alloc]
             initWithTarget:self 
             action:@selector(tapDetected:)];
            doubleTap.numberOfTapsRequired = 1;
            [self.tableView addGestureRecognizer:doubleTap];
            [doubleTap release];

    }

 - (IBAction)tapDetected:(UIGestureRecognizer *)sender 
 {
    CGPoint p = [sender locationInView:self.tableView];

    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];

   if(indexPath == nil)
   {
     NSLog(@"empty");
   }
   else
   {
     [textField resignFirstResponder];
   }
 }

我认为这将有助于...试一试吧...


1
最终我使用了滚动,因为当我在tableview上放置tapgesture时,它会导致单元格不再响应点击事件,从而无法提交单元格,因为tap gesture会吞噬该事件。非常感谢您的帮助,我可能会在将来的其他情况下需要这段代码。 - Rob

0
@property (weak, nonatomic) UITextField *activeTextField; // keeps track of whose keyboard is being displayed.

- (void)textFieldDidBeginEditing:(UITextField *)textField {
   self.activeTextField = textField;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   // if (indexPath equal to something then)
   [self.activeTextField resignFirstResponder];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接