先是Swift版本的,不建议使用,因为会出一些奇奇怪怪的问题
if let view = UIApplication.sharedApplication().keyWindow?.performSelector(Selector("firstResponder")) {
let first = view.takeRetainedValue() as? UIView
first?.resignFirstResponder()
}
下面是OC版本的。
+ (void)resignTheFirstResponder {
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
[firstResponder resignFirstResponder];
}
很多人不清楚获取当前页面的第一响应者有什么用,比如你创建了一个右滑菜单,当前页面有个输入框,正好处在编辑之中,当你右滑出菜单的时候,需要键盘放弃第一响应者的身份,
这时候使用这个方法就可以不用判断是在哪个页面,都可以放弃第一响应者。
转载至 地址:https://youshaoduo.github.io/ https://blog.csdn.net/youshaoduo/article/details/52163339
-
拓展
1,当有很多textfeild 的时候,要放弃正在响应的响应者的时候,点击完成,自动收缩键盘。如图
首先inputField.inputAccessoryView 用自己定义ATYInputAccessoryView,由于用的多所以用单例。
inputField.inputAccessoryView = [ATYInputAccessoryView shareInputAccessoryView];
代码如下ATYInputAccessoryView.h 文件
#import <UIKit/UIKit.h>
@interface ATYInputAccessoryView : UIToolbar
+(id)shareInputAccessoryView;
@end
ATYInputAccessoryView.m 文件
#import "ATYInputAccessoryView.h"
@implementation ATYInputAccessoryView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.barTintColor = [UIColor whiteColor];
UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *finish = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(done)];
[self setItems:@[space,space,finish]];
}
return self;
}
- (void)done{
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
[firstResponder resignFirstResponder];
}
+(id)shareInputAccessoryView {
static ATYInputAccessoryView *_instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[ATYInputAccessoryView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
});
return _instance;
}
@end