IQKeyboardManager是个特别好用的键盘管理的三方库。可实现输入时键盘的回收和显示对当前页面造成的影响。
一,可以用cocoapods 直接安装,也可以自己下载来导入工程
pod 'IQKeyboardManager', '~> 4.0.0'
二,使用的时候
直接导入 #import “IQKeyboardManager.h”,就可以了,当前视图控制器就会默认使用了。
注意:
如果你不使用storyboard或xib创造你的视图。你需要重写-(void)UIViewController loadview方法,需要设置一个UIScrollView实例self.view。
-(void)loadView
{
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.view = scrollView;
}
禁用IQKeyboardManager
如果你想在某个 viewcontroller 禁用 IQKeyboardManager 你应该在 ViewDidAppear 中禁用IQKeyboardManager,而在ViewWillDisappear启用它
代码
@interface HomeViewController (){ BOOL _wasKeyboardManagerEnabled;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
_wasKeyboardManagerEnabled = [[IQKeyboardManager sharedManager] isEnabled];
[[IQKeyboardManager sharedManager] setEnable:NO];
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[IQKeyboardManager sharedManager] setEnable:_wasKeyboardManagerEnabled];
}
回车键的处理
键盘的回车键处理
1)创建一个实例变量实例化IQKeyboardReturnKeyHandler 在 ViewController 的 viewDidLoad 中
代码:
@implementationViewController { IQKeyboardReturnKeyHandler *returnKeyHandler;
}
- (void)viewDidLoad
{
[super viewDidLoad];
returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
}
改变键盘上的返回键。
设置实例变量为零的dealloc方法
-(void)dealloc {
returnKeyHandler = nil;
}
UIToolbar(IQToolbar)
1)如果你不想添加一个特定的自动工具栏在键盘上方,应该添加一个类作为它的工具栏
textField.inputAccessoryView = [[UIView alloc] init];
2)如果你需要自己控制上/下/完成按钮,那么应该使用UIView类的方法,创建你的文本框工具栏。
代码:
-(void)viewDidLoad {
[super viewDidLoad];
[textField1 addDoneOnKeyboardWithTarget:self action:@selector(doneAction:)]; //Adding previous/next/done button for textField2
[textField2 addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(previousAction:) nextAction:@selector(nextAction:) doneAction:@selector(doneAction:)]; //Adding cancel/done button for textField3
[textField3 addCancelDoneOnKeyboardWithTarget:self cancelAction:@selector(cancelAction:) doneAction:@selector(doneAction:)];
}
/*! previousAction. */
-(void)previousAction:(id)button { //previousAction
} /*! nextAction. */
-(void)nextAction:(id)button {
//nextAction
} /*! doneAction. */
-(void)doneAction:(UIBarButtonItem*)barButton {
//doneAction
} /*! cancelAction. */
-(void)cancelAction:(UIBarButtonItem*)barButton { //cancelAction
}