如何在向上/向下移动时为我的视图添加平滑动画?

时间:2015-05-17 04:53:26

标签: ios objective-c uiviewanimation

我使用以下代码在启动键盘时向上/向下移动我的UIView,以防止它覆盖我的文本字段。代码效果很好,但运动并不像我喜欢的那样无缝。会喜欢一些帮助:我需要添加的代码,以使视图移动平滑而不是波涛汹涌。在此先感谢:)

更新:我将KeyboardDidShow更改为KeyboardWillShow,这样做会导致以下崩溃错误。

  

由于未捕获的异常而终止应用   ' NSInvalidArgumentException',原因:' - [ViewController   keyboardDidShow:]:无法识别的选择器发送到实例0x145e0f530

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

    [self.view endEditing:YES];
    return YES;
}


- (void)keyboardWillShow:(NSNotification *)notification
{

    // Assign new frame to your view
    [self.view setFrame:CGRectMake(0,-110,375,667)]; //here taken -20 for example i.e. your view will be scrolled to -20. change its value according to your requirement.

}

-(void)keyboardDidHide:(NSNotification *)notification
{
    [self.view setFrame:CGRectMake(0,0,375,667)];
}

2 个答案:

答案 0 :(得分:0)

尝试在[UIView animateWithDuration:animations:]

中包装帧更改
[UIView animateWithDuration:.25 animations:^{
    [self.view setFrame:CGRectMake(0,0,375,667)];
}];

答案 1 :(得分:0)

只需在动画块中添加代码:

- (void)keyboardDidShow:(NSNotification *)notification{

[UIView animateKeyframesWithDuration:1.0
                                       delay:0.0
                                     options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                                  animations:^{

                                     [self.view setFrame:CGRectMake(0,-110,375,667)];

                                  } completion:nil];

}

-(void)keyboardDidHide:(NSNotification *)notification{

[UIView animateKeyframesWithDuration:1.0
                                       delay:0.0
                                     options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                                  animations:^{

                                     [self.view setFrame:CGRectMake(0,0,375,667)];

                                  } completion:nil];
}