106

我有一个UITableView带有UITextFields 的单元格。我想在UITableView触摸背景时关闭键盘。我试图通过创建一个UIButton大小UITableView并将其放在UITableView. 唯一的问题是UIButton即使触摸在 UITableView 上也能捕捉到所有的触摸。我究竟做错了什么?

谢谢!

4

29 回答 29

204

这很容易通过创建一个UITapGestureRecognizer对象来完成(默认情况下,这将在单击时检测“手势”,因此不需要进一步自定义),指定触发手势时的目标/动作,然后附加手势识别器对象到您的表格视图。

例如,也许在您的viewDidLoad方法中:

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];

hideKeyboard方法可能如下所示:

- (void) hideKeyboard {
    [textField1 resignFirstResponder];
    [textField2 resignFirstResponder];
    ...
    ...
}

请注意,在对象内部触摸时不会触发手势UITextFieldUITableView它在背景、页脚视图、标题视图和UILabels内部单元格等上被触发。

于 2010-11-09T10:42:57.527 回答
128

如果您设置,则 UITapGestureRecognizer 解决方案适用于表格单元格选择:

gestureRecognizer.cancelsTouchesInView = NO;
于 2011-01-18T18:21:28.967 回答
61

这是执行此操作的最佳方法。就这样做

[self.view endEditing:YES];

或者

[[self.tableView superView] endEditing:YES];
于 2012-02-29T08:14:04.407 回答
56

您也可以从 Storyboard 中执行此操作: 在此处输入图像描述

于 2016-01-25T08:41:35.517 回答
22

As UITableView is a subclass of UIScrollView, implementing one delegate method below provides an extremely easy, quick solution. No need to even involve resignFirstResponder since view hierarchy introspects and finds the current responder and asks it to resign it's responder status.

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

And remember to add UIScrollViewDelegate to header file.

于 2013-05-14T18:08:51.637 回答
13

首先,scrollViewWillBeginDragging通过UIViewController添加以下内容来收听UIScrollViewDelegate

在 .h 文件中:

@interface MyViewController : UIViewController <UIScrollViewDelegate> 

在 .m 文件中:

- (void)scrollViewWillBeginDragging:(UIScrollView *)activeScrollView {

    [self dismissKeyboard];

}

然后监听其他交互:

- (void)setupKeyboardDismissTaps {

    UISwipeGestureRecognizer *swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeUpGestureRecognizer.cancelsTouchesInView = NO;
    swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
    [self.tableView addGestureRecognizer:swipeUpGestureRecognizer];

    UISwipeGestureRecognizer *swipeDownGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeDownGestureRecognizer.cancelsTouchesInView = NO;
    swipeDownGestureRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
    [self.tableView addGestureRecognizer:swipeDownGestureRecognizer];

    UISwipeGestureRecognizer *swipeLeftGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeLeftGestureRecognizer.cancelsTouchesInView = NO;
    swipeLeftGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.tableView addGestureRecognizer:swipeLeftGestureRecognizer];

    UISwipeGestureRecognizer *swipeRightGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeRightGestureRecognizer.cancelsTouchesInView = NO;
    swipeRightGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.tableView addGestureRecognizer:swipeRightGestureRecognizer];


    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];

}

然后实施dismissKeyboard

- (void)dismissKeyboard {

    NSLog(@"dismissKeyboard");

    [yourTextFieldPointer resignFirstResponder];

}

如果像我一样,您想在自定义表格单元格中关闭 UITextField 的键盘:

- (void)dismissKeyboard {

    NSLog(@"dismissKeyboard");

    CustomCellClass *customCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [customCell.textFieldInCell resignFirstResponder]; 

}

希望对搜索的人有所帮助!!

于 2011-06-30T16:01:41.367 回答
12
tableView.keyboardDismissMode = .onDrag
于 2016-07-28T19:24:19.987 回答
8

这是您的编码乐趣的快速版本:

它添加了一个轻击手势识别器,然后关闭键盘。不需要 TextField 的出口!

override func viewDidLoad() {
    super.viewDidLoad()
    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:"))
}

func handleTap(sender: UITapGestureRecognizer) {
    if sender.state == .Ended {
        view.endEditing(true)
    }
    sender.cancelsTouchesInView = false
}
于 2015-10-02T12:41:13.303 回答
8

有 Swift 3 版本,没有阻止对单元格的点击。

viewDidLoad()方法:

let dismissKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
dismissKeyboardGesture.cancelsTouchesInView = false
tableView.addGestureRecognizer(dismissKeyboardGesture)

hideKeyboard看起来像这样:

func hideKeyboard() {
    view.endEditing(true)
}
于 2017-10-30T09:57:06.187 回答
7

我是这样做的:

在您的 TableViewController 中创建一个方法来停用第一响应者(此时将是您的 TextBox)

- (BOOL)findAndResignFirstResonder:(UIView *)stView {
    if (stView.isFirstResponder) {
        [stView resignFirstResponder];
        return YES;     
    }

    for (UIView *subView in stView.subviews) {
        if ([self findAndResignFirstResonder:subView]) {
            return YES;
        }
    }
    return NO;
}

tableView:didSelectRowAtIndexPath:调用上一个方法时:

- (void)tableView:(UITableView *)tableView
                             didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    [self findAndResignFirstResonder: self.view];
    ...
}
于 2010-02-23T19:38:43.720 回答
5

我有一个UITableViewController并且实施touchesBegan:withEvent:对我不起作用。

这是有效的:

迅速:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    view.endEditing(true)
}

目标-C:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
}
于 2015-12-18T15:34:17.820 回答
4
@interface DismissableUITableView : UITableView {
}
@end

@implementation DismissableUITableView

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
 [self.superview endEditing:YES];
 [super touchesBegan:touches withEvent:event];
}

@end

然后确保在 Nib 文件中将 UITableView 的类型设置为 DismissableUITableView .....也许我可以为这个类想一个更好的名字,但你明白了。

于 2010-08-18T11:46:43.483 回答
4

如果您的目标是 iOS7,您可以使用以下方法之一:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

前者将在表格视图滚动时将键盘动画显示在屏幕外,而后者将像股票消息应用程序一样隐藏键盘。

请注意,这些是 from UIScrollView,它UITableView继承自。

于 2014-01-04T18:15:36.257 回答
3

尝试这个:

viewDidLoad(){

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))

    tableView.addGestureRecognizer(tap)

}
//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {

    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)

}
于 2019-03-22T13:27:47.610 回答
2

UITableView 是 UIScrollView 的子类。

我这样做的方式是监听用户的滚动事件,然后 resignFirstResponder。这是要在您的代码中实现的 UIScrollViewDelegate 方法;

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

在处理这类问题时,我发现最好的方法是研究每个对象和父类的委托协议(在本例中为 UITableViewDelegate、UIScrollViewDelegate。NS 对象触发的事件数量非常大且全面。它是也更容易实现协议然后继承任何东西。

于 2010-08-28T18:31:57.833 回答
2

我找到了一个很好的解决方案。

需要使用UIGestureRecognizerDelegate和方法–gestureRecognizer:shouldReceiveTouch:

将手势识别器添加到 TableView 中,如下所示:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
tapGestureRecognizer.cancelsTouchesInView = NO;
tapGestureRecognizer.delegate = self;
[self.suggestedTableView addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer release];

然后,实现shouldReceiveTouch委托方法来拒绝在 UITableViewCell 类中执行的触摸。只有在UITableViewCell 类之外执行了触摸时,才会调用hideKeyboard方法。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if([touch.view isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    // UITableViewCellContentView => UITableViewCell
    if([touch.view.superview isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    // UITableViewCellContentView => UITableViewCellScrollView => UITableViewCell
    if([touch.view.superview.superview isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    return YES; // handle the touch
}

- (void) hideKeyboard{
    [textField resignFirstResponder];
}
于 2014-09-17T08:33:58.637 回答
2

我遇到了同样的问题,这是我的解决方案,它非常适合我:

在您实现的视图或视图控制器中<UITextFieldDelegate>

(在我的情况下,我有一个UITableViewCell名为 TextFieldCell 的自定义),

声明UITapGestureRecognizer为属性:

@interface TextFieldCell : UITableViewCell <UITextFieldDelegate>
{
    UITextField *theTextField;
    UITapGestureRecognizer *gestureRecognizer;
}
@property (nonatomic,retain) UITextField *theTextField;
@property (nonatomic,retain) UITapGestureRecognizer *gestureRecognizer; 

并在您的视图/控制器中初始化它:

self.gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];

在该- (void)textFieldDidBeginEditing:(UITextField *)textField方法中,用于superView向上移动到您的 tableView 并调用addGestureRecognizer

[self.superview.superview addGestureRecognizer:gestureRecognizer];

在 中- (void)textFieldDidEndEditing:(UITextField *)textField,只需删除手势识别器:

[self.superview.superview removeGestureRecognizer:gestureRecognizer];

希望能帮助到你。

于 2012-05-22T06:01:35.167 回答
2

我希望我的单元格在选择单元格的任何部分时打开键盘,并在您单击单元格外的任何位置时关闭它。打开键盘:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    if (selected)
    {
        [self.textField becomeFirstResponder];
    }
}

(注意:我已经对单元进行了子类化,但是您可以在 的tableView:didSelectRowAtIndexPath:委托方法中轻松实现这一点UITableView

这样做意味着,使用顶级解决方案,如果您单击单元格两次,键盘会抖动,首先手势识别器尝试关闭键盘,然后重新选择单元格并尝试打开键盘。

解决方法是检查点击是否发生在当前选中的单元格内:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //gesture recognizer to close the keyboard when user taps away
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(dismissKeyboard:)];
    tap.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tap];
}

-(void)dismissKeyboard:(UIGestureRecognizer*)tapGestureRecognizer
{
    if (!CGRectContainsPoint([self.tableView cellForRowAtIndexPath:[self.tableView indexPathForSelectedRow]].frame, [tapGestureRecognizer locationInView:self.tableView]))
    {
        [self.view endEditing:YES];
    }
}
于 2014-01-09T18:38:55.707 回答
2

UITableView有一个方便的backgroundView属性,我通过它实现了这种行为而不会弄乱单元格选择,如下 Swift 所示:

let tableBackTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
tableView.backgroundView = UIView()
tableView.backgroundView?.addGestureRecognizer(tableBackTapRecognizer)
于 2017-09-28T12:40:59.473 回答
1

我正在寻找解决方案,但没有找到任何适合我的代码的东西,所以我这样做了:

http://82517.tumblr.com/post/13189719252/dismiss-keyboard-on-uitableview-non-cell-tap

它基本上是前面提到的方法的组合,但不需要子类化任何东西或创建背景按钮。

于 2011-11-23T03:54:05.063 回答
1

简单地使用 UITapGestureRecognizercancelsTouchesInView = NO意味着点击单元格和 UITextViews 也会触发隐藏。如果您有多个 UITextViews 并且您点击下一个,这很糟糕。键盘将开始隐藏,然后下一个 textView 成为 firstResponder 并且键盘再次可见。为避免这种情况,请检查点击位置并仅在点击不在单元格上时隐藏键盘:

// init
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapTableView:)];
tapRecognizer.cancelsTouchesInView = NO;
[self.tableView addGestureRecognizer:tapRecognizer];


// Hide on tap
- (void)didTapTableView:(UITapGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:tap.view];
    [self.view endEditing:!CGRectContainsPoint([self.tableView rectForRowAtIndexPath:[self.tableView indexPathForRowAtPoint:point]], point)];
}

为了scrollViewWillBeginDragging:被触发,tableView 的scrollEnabled属性必须是YES

// Hide on scroll
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
于 2014-05-28T00:43:14.960 回答
1

tableView.keyboardDismissMode = .onDrag // .interactive

于 2020-07-17T13:15:03.463 回答
1

斯威夫特 4/4.2/5

您还可以在点击单元格时关闭键盘 - 在执行任何其他操作之前。

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    view.endEditing(true)
    // Do something here
    }

于 2020-01-20T03:11:21.157 回答
0

@mixca 的答案非常有用,但是如果我有与 UITextField 不同的东西怎么办。我认为通过使用递归函数搜索主视图的所有子视图来处理它的最佳方法,请查看下面的示例

- (BOOL)findAndResignFirstResponder {
if (self.isFirstResponder) {
    [self resignFirstResponder];
    return YES;
}

    for (UIView *subView in self.subviews) {
        if ([subView findAndResignFirstResponder]) {
            return YES;
        }
    }
    return NO;
}

你也可以把这个方法放到你的实用程序类中,并可以像@mixca's answer那样使用轻击手势。

于 2014-09-24T07:45:08.767 回答
0

如果您愿意子类化(呃!)您的表格视图,这样的事情可能会起作用:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

   BOOL backgroundTouched = YES;

   for (UITouch *touch in touches) {
      CGPoint location = [touch locationInView:self];
      for (UITableViewCell *cell in self.visibleCells) {
         if (CGRectContainsPoint(cell.frame, location)) {
            backgroundTouched = NO;
            break;
         }
      }
   }

   if (backgroundTouched) {
      for (UITableViewCell *cell in self.visibleCells) {
         // This presumes the first subview is the text field you want to resign.
         [[cell.contentView.subviews objectAtIndex:0] resignFirstResponder];
      }
   }

   [super touchesBegan:touches withEvent:event];
}
于 2010-05-11T22:44:48.803 回答
0

许多有趣的答案。我想将不同的方法编译到我认为最适合 UITableView 场景的解决方案中(这是我通常使用的那个):我们通常想要的基本上是在两种情况下隐藏键盘:在文本 UI 元素之外点击,或向下/向上滚动 UITableView。第一个场景我们可以通过 TapGestureRecognizer 轻松添加,第二个场景通过 UIScrollViewDelegate scrollViewWillBeginDragging: 方法。首先,隐藏键盘的方法:

   /**
     *  Shortcut for resigning all responders and pull-back the keyboard
     */
    -(void)hideKeyboard
    {
        //this convenience method on UITableView sends a nested message to all subviews, and they resign responders if they have hold of the keyboard
        [self.tableView endEditing:YES];

    }

此方法会为 UITableView 视图层次结构中的子视图的任何 textField UI 签名,因此它比单独为每个元素单独签名更实用。

接下来,我们通过外部的 Tap 手势来处理关闭,其中:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupKeyboardDismissGestures];

}

- (void)setupKeyboardDismissGestures
{

//    Example for a swipe gesture recognizer. it was not set-up since we use scrollViewDelegate for dissmin-on-swiping, but it could be useful to keep in mind for views that do not inherit from UIScrollView
//    UISwipeGestureRecognizer *swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
//    swipeUpGestureRecognizer.cancelsTouchesInView = NO;
//    swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
//    [self.tableView addGestureRecognizer:swipeUpGestureRecognizer];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    //this prevents the gestureRecognizer to override other Taps, such as Cell Selection
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];

}

将 tapGestureRecognizer.cancelsTouchesInView 设置为 NO 是为了避免手势识别器覆盖 UITableView 的正常内部工作(例如,不干扰单元格选择)。

最后,要处理在 UITableView 上/下滚动时隐藏键盘,我们必须实现 UIScrollViewDelegate 协议的 scrollViewWillBeginDragging: 方法,如:

.h 文件

@interface MyViewController : UIViewController <UIScrollViewDelegate>

.m 文件

#pragma mark - UIScrollViewDelegate

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hideKeyboard];
}

我希望它有帮助!=)

于 2014-05-23T11:26:52.323 回答
0

为什么要创建一个充满文本字段的表格?您应该为包含文本字段的每一行使用详细视图。推送详细视图时,请确保调用“[myTextField becomeFirstResponder]”,以便用户只需单击表格列表即可开始编辑。

于 2010-02-25T07:13:52.693 回答
0

这是我最终制作作品的方式。我结合了来自不同答案的建议和代码。特点:关闭键盘,在编辑和设置“下一步”和“完成”键盘返回类型时在键盘上方移动文本字段。用更多字段替换“...”

static const CGFloat ANIMATION_DURATION = 0.4;
static const CGFloat LITTLE_SPACE = 5;
CGFloat animatedDistance;
CGSize keyboardSize;

@interface ViewController () <UITextFieldDelegate>
 @property (weak, nonatomic) IBOutlet UITextField *firstNameTXT;
  .....// some other text fields
 @property (weak, nonatomic) IBOutlet UITextField *emailTXT;
@end

@implementation ViewController
- (void)viewDidLoad{
.....
// add tap gesture to help in dismissing keyboard
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(tapScreen:)];// outside textfields

[self.view addGestureRecognizer:tapGesture];

// set text fields return key type to Next, last text field to Done
[self.firstNameTXT setReturnKeyType:UIReturnKeyNext];
.....
[self.emailTXT setReturnKeyType:UIReturnKeyDone];

// set text fields tags
[self.firstNameTXT setTag:0];
....// more text fields
[self.emailTXT setTag:5];

// add keyboard notification
[[NSNotificationCenter defaultCenter] addObserver:self     selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self      selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

// dismiss keyboard when tap outside text fields
- (IBAction)tapScreen:(UITapGestureRecognizer *)sender {
  if([self.firstNameTXT isFirstResponder])[self.firstNameTXT resignFirstResponder];
  ...
  if([self.emailTXT isFirstResponder])[self.emailTXT  resignFirstResponder];

  }
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
   if(textField.returnKeyType==UIReturnKeyNext) {
     // find the text field with next tag
     UIView *next = [[textField superview] viewWithTag:textField.tag+1];
     [next becomeFirstResponder];
   } else if (textField.returnKeyType==UIReturnKeyDone || textField.returnKeyType==UIReturnKeyDefault) {
    [textField resignFirstResponder];
 }
return YES;
}

// Moving current text field above keyboard
-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField{
   CGRect viewFrame = self.view.frame;
   CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
   CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
   CGFloat textFieldBottomLine = textFieldRect.origin.y + textFieldRect.size.height + LITTLE_SPACE;//

   CGFloat keyboardHeight = keyboardSize.height;

   BOOL isTextFieldHidden = textFieldBottomLine > (viewRect.size.height - keyboardHeight)? TRUE :FALSE;
  if (isTextFieldHidden) {
    animatedDistance = textFieldBottomLine - (viewRect.size.height - keyboardHeight) ;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
  }
  return YES;
}

-(void) restoreViewFrameOrigionYToZero{
  CGRect viewFrame = self.view.frame;
  if (viewFrame.origin.y != 0) {
    viewFrame.origin.y = 0;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
  }
}

-(void)keyboardDidShow:(NSNotification*)aNotification{
   NSDictionary* info = [aNotification userInfo];
   keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
 }

-(void)keyboardDidHide:(NSNotification*)aNotification{
   [self restoreViewFrameOrigionYToZero];// keyboard is dismissed, restore frame view to its  zero origin
}
@end
于 2014-08-06T04:55:43.973 回答
0

如果你想在按下返回键时关闭键盘,你可以简单地在 textField 应该返回方法中添加以下代码,即:

- (BOOL)textFieldShouldReturn:(UITextField *)atextField
{
   [textField resignFirstresponder];
}

某些文本字段可能具有选择器视图或其他一些作为子视图,因此在这种情况下,上述方法不起作用,因此在这种情况下,我们需要使用 UITapGestureRecognizer 类,即将以下代码片段添加到 viewDidLoad 方法,即:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(dismissKeyboard)];

    [self.view addGestureRecognizer:tap];

现在只需将辞职响应者添加到选择器方法中,即:

-(void)dismissKeyboard 
{
    [textField resignFirstResponder];
}

希望对你有帮助,谢谢:)

于 2012-02-18T07:30:28.383 回答