zoukankan      html  css  js  c++  java
  • ios 去掉屏幕键盘的方法

    //定义两个文本框
    UITextField *textName;
    UITextField *textSummary;
    
    //点击return 按钮 去掉
    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    //点击屏幕空白处去掉键盘
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        [self.textName resignFirstResponder];
        [self.textSummary resignFirstResponder];
    }

           在iOS开发中,对UITextField进行编辑的时候键盘会自己弹出来。在编辑完成的时候,需要将键盘隐藏掉。隐藏键盘有很多种实现方法,最常见的是把TextField的firstResponder resign掉,即[textField resignFirstResponder]。

    下面介绍的是如何在键盘显示的时候,点击屏幕除了键盘以外的任何地方,将键盘隐藏。

    基本思想如下: 1. 在ViewController载入的时候,将键盘显示和消失的Notification添加到self.view里。 2. 分别在键盘显示和消失时添加和删除TapGestureRecognizer 就这么简单。

    示例代码如下: UIViewController的源代码里:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
      
      [self setUpForDismissKeyboard];
    }
    - (void)setUpForDismissKeyboard {
    
      NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
      UITapGestureRecognizer *singleTapGR =
      [[UITapGestureRecognizer alloc] initWithTarget:self
                                              action:@selector(tapAnywhereToDismissKeyboard:)];
      NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
      [nc addObserverForName:UIKeyboardWillShowNotification
                      object:nil
                       queue:mainQuene
                  usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                  }];
      [nc addObserverForName:UIKeyboardWillHideNotification
                      object:nil
                       queue:mainQuene
                  usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                  }];
    }
    
    - (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
      [self.view endEditing:YES];
    }
  • 相关阅读:
    tabbar 旋转指定的页面
    GDAL中文路径不能打开&Shp文件字段属性值中文乱码
    Project : error PRJ0019: 工具从"Moc'ing xxx.h..."
    详解Android中的屏幕方向
    qt中获取文件路径和文件名
    vs2005下Qt项目中修改exe图标的方法
    Qt & C/C++统计运行时间
    Qt 中Treewidget添加右键菜单
    QT 中文乱码解决方案
    Qt多线程应用QRunnable显示进度条示例
  • 原文地址:https://www.cnblogs.com/wyqfighting/p/3164551.html
Copyright © 2011-2022 走看看