How do I resignFirstResponder when I click outside of a UITextField onto a UITableView

与世无争的帅哥 提交于 2019-12-10 04:24:46

问题


I am having trouble getting the keyboard in my iPhone app to go away because the UIView even when made a controller is not touchable because of the fact that I have a UITableView taking up the rest of the available screen.

I was curious to know how I would go resigning the keyboard aka firstResponder by clicking onto the UITableView? Is there a way to monitor a touch event on the UITableView even if it is not to select a clickable cell.

Basically, I know how to resign the keyboard if the cell fires the event but, if I click on a non - clickable part of the UITableView I would still like the keyboard to go away.


回答1:


2 options:

  • In your viewController, respond to the table's scroll callback and resign the responder
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     [self.view endEditing:YES];
}
  • You can always add a UITapGestureRecognizer to the table/view and resign the responder from there

Personally I usually do it on table scroll, since I don't like a single tap to dismiss the keyboard.




回答2:


   - (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];
   }
 }

I think it will help... try it..




回答3:


Adding a tap gesture recognizer is an interesting solution, but there's an alternative and you don't need to code anything!

You can set in Interface Builder the property keyboardDismissMode to "Dismiss on drag" for your table view. It's a property inherited from UIScrollView and whenever you scroll your table view, the keyboard is dismissed.




回答4:


@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];
}


来源:https://stackoverflow.com/questions/9503172/how-do-i-resignfirstresponder-when-i-click-outside-of-a-uitextfield-onto-a-uitab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!