如何让键盘弹入弹出更平滑.

1.注册通知大家应该都是知道的

//使用NSNotificationCenter 鍵盤出現時[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWasShown:)                                      name:UIKeyboardWillShowNotificationobject:nil];//使用NSNotificationCenter 鍵盤隐藏時[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillBeHidden:)                                      name:UIKeyboardWillHideNotificationobject:nil];

然后UIView动画...然而那是非常不协调的.

我们还得获取它的持续时间和动画类型

- (void)keyboardWasShown:(NSNotification*)aNotification{NSDictionary* info = [aNotification userInfo];//键盘尺寸CGSizekbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;//持续时间CGFloatduration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];//动画类型NSIntegeranType = [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey]integerValue];  [UIViewanimateKeyframesWithDuration:duration delay:0options:anType animations:^{CGRectrect = weakKeyView.frame;                rect.origin.y-= kSize.height;                weakKeyView.frame= rect;  } completion:^(BOOLfinished) {  }];}

2.  用键盘出现、消失通知在退到后台进进到前台应该做的处理.

接上面,你要是添加了键盘出现和消失的通知,然后让TextField获取第一响应,这个时候你要是点Home键推到后台,然后再点App回到前台,你就会发现:

你在通知的方法中有动画处理的组件消失了...

经过不懈的监听,找到了解决办法:

在Appdelegate.m里面找到进入后台、进入前台的方法,然后发送通知

创建通知

/进入前台[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(enterForeground)                      name:@"EnterForeground"object:nil];//进入后台[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(enterBackground)                      name:@"EnterBackground"object:nil];

//进入后台- (void)applicationDidEnterBackground:(UIApplication*)application {//创建一个消息对象NSNotification* notice = [NSNotificationnotificationWithName:@"EnterBackground"object:niluserInfo:nil];//发送消息[[NSNotificationCenterdefaultCenter]postNotification:notice];}//进入前台- (void)applicationWillEnterForeground:(UIApplication*)application {//创建一个消息对象NSNotification* notice = [NSNotificationnotificationWithName:@"EnterForeground"object:niluserInfo:nil];//发送消息[[NSNotificationCenterdefaultCenter]postNotification:notice];}

在进到后台的方法中注销键盘出现和消失的通知

- (void)enterBackground{    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillShowNotificationobject:nil];    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillHideNotificationobject:nil];}

在进入前台的方法中再次添加为键盘出现和消失的通知的观察者

dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

[self addKeyNofi];

});

这样就解决了这个问题,要注意的是一定要延迟0.5秒左右再添加为观察者.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容