我们在有些应用场景下,比如搞定聊天时的输入窗等时,需要完成一些动画。我们需要准确知道键盘弹出的duration啊,frame啊,还有curve。显然设置固定值时是不可取的,那我们又如何知道这些信息的。其实很简单,而且iOS3.2以上就有了官方的方法。
首先,我们要监听键盘弹出事件:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
好了,之后,实现监听方法,同时获取相关信息:
- (void)keyboardWillShow:(NSNotification *)note
{
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
double keyboardTransitionDuration;
[[note.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&keyboardTransitionDuration];
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[note.userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&keyboardTransitionAnimationCurve];
//拿到了就可以浪动画了
}
PS:键盘的frame是相对于整个window的,所以他得x,y不是你想要的你的view里的对应位置。不过有解决办法:
keyboardBounds = [selfconvertRect:keyboardBounds toView:/*你的view*/];
这样就可以转换一下
键盘消失的方法类似,同样地监听下键盘消失的通知就好了。