[关闭]
@zwenqiang 2015-10-10T18:02:17.000000Z 字数 1164 阅读 2376

UITextField编辑后关闭虚拟键盘

IOS


使用ViewController的全局触摸方法touch

  1. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  2. [self.roomField resignFirstResponder];
  3. [self.buildField resignFirstResponder];
  4. }

实现UITextFieldDelegate代理方法

  1. self.roomField.delegate = self;
  2. - (BOOL)textFieldShouldReturn:(UITextField *)textField{
  3. // called when 'return' key pressed. return NO to ignore.
  4. NSLog(@"按下了return键");
  5. [textField resignFirstResponder];
  6. return YES;
  7. }

通过点击return按钮关闭键盘

当用户按下Return按钮时,将触发“did end on exit”事件,此时我们需要让文本字段取消控件,以关闭键盘。

  1. [self.roomField addTarget:self action:@selector(closeTextFieldKeyBorad:) forControlEvents:UIControlEventEditingDidEndOnExit];
  2. # 或者在Interface Builder中按command+2 选择Did End on Exit旁边的圆圈拖到File’s Owner图标,并将它连接到closeTextFieldKeyBorad操作。
  3. - (void)closeTextFieldKeyBorad: (id)sender{
  4. [sender resignFirstResponder];
  5. NSLog(@"关闭键盘%@",sender);
  6. }

在主界面上新建一个UIControl控件,监听触摸事件

  1. UIControl *control = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
  2. [control addTarget:self action:@selector(closeTextFieldKeyBorad:) forControlEvents:UIControlEventTouchDown];
  3. [self.view addSubview:control];
  4. - (void)closeTextFieldKeyBorad: (id)sender{
  5. NSLog(@"开始关闭键盘");
  6. [self.roomField resignFirstResponder];
  7. NSLog(@"关闭键盘%@",sender);
  8. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注