Objective-C 代码实例方式一
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
如果一个view上有许多TextField,可以直接
[self.view endEditing:YES];
Objective-C 代码实例方式二
[[self findFirstResponderBeneathView:self] resignFirstResponder];[[self findFirstResponderBeneathView:self] becomeFirstResponder];//打开键盘
- (UIView*)findFirstResponderBeneathView:(UIView*)view {// Search recursively for first responderfor ( UIView *childView in view.subviews ) {if ( [childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder] ) return childView;UIView *result = [self findFirstResponderBeneathView:childView];if ( result ) return result;}return nil;
}
Swift方式一
UIApplication.sharedApplication().keyWindow?.endEditing(true)
Swift方式二
func findFirstResponderBeneathView(view: UIView) -> () {for childView in view.subviews {let isChildFirstResponder = childView.isFirstResponder()let isChildResponderSelector = childView.respondsToSelector("isFirstResponder")if isChildFirstResponder && isChildResponderSelector {childView.resignFirstResponder()}self.findFirstResponderBeneathView(childView as! UIView)}}