iOS开发常见问题

收起键盘的几种方法

2016-07-03  本文已影响894人  sculg

在项目中,经常会用到文字输入框(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];
上一篇下一篇

猜你喜欢

热点阅读