iOS 开发之 - 关闭键盘 退出键盘 的5种方式

2020-01-18 15:39:09王振洲

iOS 开发之 - 关闭键盘 退出键盘 的5种方式

 1、点击编辑区以外的地方(UIView)

2、点击编辑区域以外的地方(UIControl)

3、使用制作收起键盘的按钮

4、使用判断输入字元

5、关于键盘遮蔽的问题

1,点击编辑区以外的地方(UIView)

这是一种很直觉的方法,当不再需要使用虚拟键盘时,只要点击虚拟键盘和编辑区域外的地方,就可以将键盘收起,下面程式码是在 UIView 中内建的触碰事件方法函式,您可以参考 Touch Panel / 触碰萤幕 / 压力感应器的基本使用方式一文,找到更多关于触碰事件的方法函式。


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
  if (![myTextView isExclusiveTouch]) { 
    [myTextView resignFirstResponder]; 
  } 
}

如果要使用此方式请务必记得,你操作画面的 Custom Class 一定要是 UIView 才行。
画面的 Custom Class 为 UIView

2. 点击编辑区域以外的地方(UIControl)

收起虚拟键盘的方式与前一种相同,但是如果你的触碰事件里已经且写满了程式码,那么就可以考虑使用,UIControl 的 Touch Up Inside 事件来收起键盘,方法是将以下程式码与 UIControl 的 Touch Up Inside 事件连结即可。


- (IBAction)dismissKeyboard:(id)sender { 
  [myTextView resignFirstResponder]; 
}

 如果要使用此方式请务必记得,你操作画面的 Custom Class 一定要是 UIControl 才行。

画面的 Custom Class 为 UIControl

将收起键盘的方法与 UIControl 事件连结

 3. 使用制作收起键盘的按钮

当没有编辑区域以外的地方可供点击来收起键盘,自己制作一个按钮来收起目前的虚拟键盘,也是一个不错的方法,由于按钮必须在虚拟键盘出现才能显示于画面上,因此必须借用 NSNotificationCenter 来帮助我们判断目前键盘的状态。
首先在 viewDidLoad: 事件中,向 NSNotificationCenter 进行註册,告诉 NSNotificationCenter 我们的 doneButtonshow: 方法函式。


- (void)viewDidLoad { 
  [super viewDidLoad]; 
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (doneButtonshow:) name: UIKeyboardDidShowNotification object:nil]; 
}

现在每当虚拟键盘出现时,就会自动呼叫我们自定义的 doneButtonshow: 方法函式,接下来只要在该方法函式里定义按钮出现的方法即可。


-(void) doneButtonshow: (NSNotification *)notification { 
  doneButton = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 
  doneButton.frame = CGRectMake(0, 228, 70, 35); 
  [doneButton setTitle:@"完成编辑" forState: UIControlStateNormal]; 
  [doneButton addTarget: self action:@selector(hideKeyboard) forControlEvents: UIControlEventTouchUpInside]; 
  
  [self.view addSubview:doneButton]; 
}