庫的下載鏈接:https://github.com/hackiftekhar/IQKeyboardManager
IQKeyboardManager作為一款簡單實用的工具,為我們的開發提供了很多的便利。它的功能不再做過多的介紹,這里主要分享一下我在使用IQKeyboardManager時,對toolbar中"Done"按鈕事件的捕獲。
IQKeyboardManager為我們提供了在toolbar上添加按鈕的方法:
[textField addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(customPrevious:) nextAction:@selector(customNext:) doneAction:@selector(customDone:)];
但是如果只是想捕獲"Done"按鈕的事件,來進行提交等操作,使用這個方法還要實現相應按鈕的方法,又顯得過于麻煩。
在查看了IQKeyboardManager的源碼后,在IQKeyboardManager.m中可以找到"Done"按鈕的方法:
-(void)doneAction:(IQBarButtonItem*)barButton
在此方法中,可以找到現在為第一響應的textField/textView,這時再對"Done"按鈕的事件進行自定義就變得容易多了。我使用了tag對textField進行了標記。
UITextField * textField=[[UITextField alloc] initWithFrame:CGRectMake(50, 150, 150, 30)];
textField.tag=50001;//設置一個項目中唯一的tag值
[self.view addSubview:textField];
在doneAction中通過通知的方式傳遞事件
-(void)doneAction:(IQBarButtonItem*)barButton
{
//If user wants to play input Click sound. Then Play Input Click Sound.
if (_shouldPlayInputClicks)
{
[[UIDevice currentDevice] playInputClick];
}
UIView *textFieldRetain = _textFieldView;
BOOL isResignedFirstResponder = [self resignFirstResponder];
if (isResignedFirstResponder == YES &&
textFieldRetain.doneInvocation)
{
[textFieldRetain.doneInvocation invoke];
}
//發送通知
if (textFieldRetain.tag==50001) {
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"doneAction" object:nil userInfo:nil]];
}
}
最后在相應的viewcontroller中接收這個通知就可以了。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(done:) name:@"doneAction" object:nil];
- (void)done:(NSNotification *)notification{
//done按鈕的操作
}
總結:直接對IQKeyboardManager的源碼進行添加,在不破壞原有功能的情況下實現了功能。但是在cocoapods中,因為不能修改第三方庫中的源碼,所以只能把IQKeyboardManager拖到工程中使用才可以實現,不過IQKeyboardManager不用引入任何的framework,也不會造成很大的麻煩。如果有其他更好的方法,歡迎大家進行交流。