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 responder
for ( 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)
}
}