iOS自動處理鍵盤事件的第三方庫:IQKeyboardManager


我們寫界面要考慮很多用戶體驗問題,鍵盤事件的響應就是比較麻煩的一種。我們需要監聽鍵盤事件,考慮點擊背景收起鍵盤、考慮鍵盤遮擋輸入框問題等等,而且每個界面都要做這么一套。這個庫幫我們解決了這個事情。

這個庫的下載地址:https://github.com/hackiftekhar/IQKeyboardManager

這個庫是一個單例,它一旦生效,全項目任何界面都有效。讓它生效的代碼可以寫在任意位置,我寫在AppDelegate里。

?
1
2
3
4
5
6
7
8
9
10
- ( BOOL )application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     
     IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
     manager.enable = YES;
     manager.shouldResignOnTouchOutside = YES;
     manager.shouldToolbarUsesTextFieldTintColor = YES;
     manager.enableAutoToolbar = NO;
     
     return  YES;
}

 

enable控制整個功能是否啟用。

shouldResignOnTouchOutside控制點擊背景是否收起鍵盤。

shouldToolbarUsesTextFieldTintColor 控制鍵盤上的工具條文字顏色是否用戶自定義。

enableAutoToolbar控制是否顯示鍵盤上的工具條。

以上設置,就啟用了這個庫。

使用方法,代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#import "ViewController.h"
 
@interface ViewController ()
 
@property (nonatomic, strong) IQKeyboardReturnKeyHandler    *returnKeyHandler;
 
@end
 
@implementation ViewController
 
- ( void )viewDidLoad {
     [super viewDidLoad];
     
     self.returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
     self.returnKeyHandler.lastTextFieldReturnKeyType = UIReturnKeyDone;
     self.returnKeyHandler.toolbarManageBehaviour = IQAutoToolbarBySubviews;
}
 
- ( void )dealloc
{
     self.returnKeyHandler = nil;
}
 
@end

 

設置returnKeyHandler,可以點擊鍵盤上的next鍵,自動跳到下一個輸入框。最后一個輸入框點擊done自動收起鍵盤。

運行后,可以看到輸入框隨着鍵盤的彈出自動上下浮動。點擊背景,鍵盤收起。全自動了。

這個庫默認支持UITextField、UITextView、UIWebView、UIScrollView、UITableView、UICollectionView

最后要注意一點,它可以自動計算多個textField之間的先后順序,排列依據是看addSubView的先后順序。

 

關於previous/next按鈕不出現的解決辦法:

Considering Previous/Next buttons for textField inside customViews:-

If your textFields are on different customView and do not show previous/next to navigate between textField. Then you should create a SpecialView subclass of UIView, then put all customView inside SpecialView, then register SpecialView class using -(void)considerToolbarPreviousNextInViewClass:(Class)toolbarPreviousNextConsideredClass method in AppDelegate.(#154#179)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[IQKeyboardManager sharedManager] considerToolbarPreviousNextInViewClass:[SpecialView class]];
    return YES;
}
添加上面的代碼,並把所有想要跳轉(previous/next)textfield的superView(所有textfield)類型改為
SpecialView即可。
我是將xib中的View的class直接改為子定義的View(此View什么代碼都沒有,只是用來包裝);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM