当前位置: 代码迷 >> 综合 >> iOS关闭键盘简单实现(objc/swift)
  详细解决方案

iOS关闭键盘简单实现(objc/swift)

热度:85   发布时间:2023-12-06 09:13:39.0

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)}}