2012年6月4日 星期一

如何取得Keyboard Rect


註冊 keyboard 通知 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];  
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

//鍵盤顯示

-(void)keyboardDidShow:(id)sender
{
    NSDictionary * info = [sender userInfo];  
    NSValue * beginValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    NSValue * endValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect beginRect = [beginValue CGRectValue];
    CGRect endRect = [endValue CGRectValue];
    
    double duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    [UIView beginAnimations:@"keyboardDidShow" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];
    
    //鍵盤剛要升起的Rect
    NSLog(@"keyboardDidShow Begin:%@",NSStringFromCGRect(beginRect));
       //鍵盤升起完成的Rect
    NSLog(@"keyboardDidShow End:%@",NSStringFromCGRect(endRect));

    
    [UIView commitAnimations];

}

//鍵盤隱藏

-(void)keyboardDidHide:(id)sender
{
    NSDictionary * info = [sender userInfo];  
    NSValue * beginValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    NSValue * endValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect beginRect = [beginValue CGRectValue];
    CGRect endRect = [endValue CGRectValue];
    
    double duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    [UIView beginAnimations:@"keyboardDidShow" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];
    
    //鍵盤剛要落下的Rect
    NSLog(@"keyboardDidHide Begin:%@",NSStringFromCGRect(beginRect));
      //鍵盤落下完成的Rect
    NSLog(@"keyboardDidHide End:%@",NSStringFromCGRect(endRect));

    
    [UIView commitAnimations];
}


沒有留言: