2012年2月24日 星期五

監聽 UIKeyboard 事件

點擊 UITextField 時會出現鍵盤,想要在鍵盤上放 UIToolbar 並跟隨鍵盤上下滑動,可以使用以下方法:

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];
}

沒有留言:

張貼留言