在键盘顶部显示文本视图时改进动画

时间:2014-01-24 02:49:30

标签: ios objective-c uitextview uiviewanimation uikeyboard

我正在制作动画,以便在广播UIKeyboardWillShowNotification时显示顶部键盘上的文字视图,如下所示

-(void) keyboardWillShow:(NSNotification *)notification{
    // get keyboard size and loctaion
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    __block CGRect containerFrame = containerView.frame;

    containerFrame.origin.y = self.view.bounds.size.height - (kbSize.height + containerFrame.size.height);
    [UIView animateWithDuration:[duration doubleValue]
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         containerView.frame = containerFrame;
                     } completion:^(BOOL finished) {
                         nil;
                     }
     ];
}

动画不够好。如果你可以尝试一下,在动画结束时会看到小问题。

我用Google搜索并发现还有另一种方法可以制作动画并且效果很好:

-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];

    // get a rect for the textView frame
    CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];

    // set views with new info
    containerView.frame = containerFrame;


    // commit animations
    [UIView commitAnimations];
}

但是,根据文档,我们不建议在Ios 4及更高版本中使用此动画......

我不能说我的代码与后者相比有任何差异。为什么我的代码不能做完美的动画。如果您有任何想法,请提供帮助。

1 个答案:

答案 0 :(得分:4)

这是动画曲线。您引用的示例是将其动画曲线及其持续时间与键盘的持续时间相匹配。你的代码没有。您的结构看起来应该更像这样:

NSNumber* curve = info[UIKeyboardAnimationCurveUserInfoKey]; // *
NSNumber* duration = info[UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:duration.floatValue delay:0
                    options:curve.integerValue << 16 // *
                 animations: ^{ // ...