收起鍵盤的幾種方法

在項目中,經常會用到文字輸入框(UITextField、UITextView)。當用戶點擊他們會自動彈出鍵盤(注意:在模擬器上不會彈出),但是用戶輸入完成之后,收起鍵盤的操作卻需要去監聽用戶的操作并通過回調實現。這里我總結幾個常用的收起鍵盤的方法。

首先要讓存放輸入框的類聲明的UITextField代理協議,這里是直接放在一個ViewController上:

@interface TestViewController ()<UITextFieldDelegate>

我們按住Command點擊UITextFieldDelegate進去查看這個協議的方法,發現協議需要實現的方法都是可選的。

protocol UITextFieldDelegate <NSObject>
@optional
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;          // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField;             // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text
- (BOOL)textFieldShouldClear:(UITextField *)textField;               // called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField;              // called when 'return' key pressed. return NO to ignore.
@end

為了方便,我們把UITextField設置成屬性。

@property (nonatomic, strong) UITextField *testField;

創建一個UITextField:

_testField = [UITextField new];
[_testField setFrame:CGRectMake(50, self.view.frame.size.height*0.5, self.view.frame.size.width-100, 30)];
_testField.delegate = self;
_testField.backgroundColor = [UIColor grayColor];
_testField.placeholder = @"請在此輸入文字";
_testField.returnKeyType = UIReturnKeyDone;
[self.view addSubview:_testField];

收起鍵盤之方法一:通過UITextFieldDelegate協議監聽鍵盤的return按鈕時都被點擊收回鍵盤。

我們按住Commond鍵點擊returnKeyType,進去會看到returnKeyType是一個枚舉類型,也就是鍵盤上的返回按鈕的類型。

typedef NS_ENUM(NSInteger, UIReturnKeyType) {
    UIReturnKeyDefault,
    UIReturnKeyGo,
    UIReturnKeyGoogle,
    UIReturnKeyJoin,
    UIReturnKeyNext,
    UIReturnKeyRoute,
    UIReturnKeySearch,
    UIReturnKeySend,
    UIReturnKeyYahoo,
    UIReturnKeyDone,
    UIReturnKeyEmergencyCall,
    UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
};

這里的returnKeyType設置類型,只會影響鍵盤上turnkey位置將顯示的文字,如UIReturnKeyDefault顯示“換行”,UIReturnKeyGo顯示“前往”,UIReturnKeyGoogle顯示“搜索”,UIReturnKeyDone顯示“完成”。而它的實際點擊效果需要在UITextFieldDelegate的代理方法里面去實現。這里需要實現的是如下方法:

- (BOOL)textFieldShouldReturn:(UITextField *)textField;

具體實現方法如下:

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_testField resignFirstResponder];
    return YES;
}

收起鍵盤之方法二:點擊鍵盤背景,通過監聽視圖的觸摸事件來收回鍵盤。

觸摸的對象是視圖,而視圖的類UIView繼承了UIRespnder類,但是要對事件作出處理,還需要重寫UIResponder類中定義的事件處理函數。根據不通的觸摸狀態,程序會調用相應的處理函數,這些函數包括以下幾個:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesCancelled:(nullable NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEstimatedPropertiesUpdated:(NSSet * _Nonnull)touches NS_AVAILABLE_IOS(9_1);

這是實現父類的方法,我們只需用其中的:
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
具體的實現如下:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (![_testField isExclusiveTouch]) {
[_testField resignFirstResponder];
}
}

isExclusiveTouch 決定當前視圖是否是處理觸摸事件的唯一對象,默認值是0;

收起鍵盤之方法三:點擊鍵盤背景,通過監聽手勢UITapGestureRecognizer來收回鍵盤。

UIKit中包含了UIGestureRecognizer類,用于檢測發生在設備中的手勢。UIGestureRecognizer是一個抽象類,定義了所有手勢的基本行為,它有下面一些子類用于處理具體的手勢:

1、拍擊UITapGestureRecognizer (任意次數的拍擊)  
2、向里或向外捏UIPinchGestureRecognizer (用于縮放)  
3、搖動或者拖拽UIPanGestureRecognizer  
4、滑動UISwipeGestureRecognizer (以任意方向)  
5、旋轉UIRotationGestureRecognizer (手指朝相反方向移動)  
6、長按UILongPressGestureRecognizer 

對于不同類型的手勢識別器,具有不同的配置屬性。比如UITapGestureRecognizer,可以配置拍擊次數。界面接收到手勢之后,可以發送一 個消息,用于處理響應手勢動作后的任務。當然,不同的手勢識別器,發送的消息方法也會有所不同。

我們這里主要用其中的UITapGestureRecognizer。
創建一個UITapGestureRecognizer:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
//設置成NO表示當前控件響應后會傳播到其他控件上,默認為YES。
tapGestureRecognizer.cancelsTouchesInView = NO;
//將觸摸事件添加到view上
[self.view addGestureRecognizer:tapGestureRecognizer];

添加響應手勢的任務:

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [_testField resignFirstResponder];
}

收起鍵盤之方法四:如果輸入框的是處于UIScrollView、或UITableView中,還可以通過實現UIScrollViewDelegate協議,監聽用戶的滑動操作并收起鍵盤。

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

上面的方法,有一個問題:就是必須找到_testField對象,并且向它發送resignFirstResponder消息。 有方法可以不需要找到對象,直接執行收回鍵盤的操作,用下面的替換resignFirstResponder:

  [[[UIApplication sharedApplication] keyWindow] endEditing:YES];

或者:

 [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容