NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
建立2個監聽,當UIKeyboard出現或消失時都會通知selector裡的method
- (void)keyboardWillShow:(NSNotification *)notification
{
//透過 notification userInfo 可以得到UIKeyboard的資訊
NSDictionary *userInfo = [notification userInfo];
NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect kf = [aValue CGRectValue];
[self slideViewWithOptions:userInfo PosY:kf.size.height];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
[self slideViewWithOptions:userInfo PosY:0];
}
- (void)slideViewWithOptions:(NSDictionary *)options PosY:(CGFloat)PosY
{
NSTimeInterval animationDuration;
UIViewAnimationCurve animationCurve;
CGRect keyboardEndFrame;
//取得UIKeyboard滑動的動畫曲線、秒數與位置
[[options objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
[[options objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
[[options objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
int toolBarHeight = toolBar.frame.size.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:animationCurve];
[UIView setAnimationDuration:animationDuration];
CGRect frame = toolBar.frame;
frame.origin.y = CGRectGetHeight(self.view.frame) - toolBarHeight - PosY;
toolBar.frame = frame;
[UIView commitAnimations];
}
沒有留言:
張貼留言