iOS动画主要UIViewController的视图高度

时间:2014-09-23 13:36:34

标签: ios objective-c uiviewcontroller

我有一个文本字段固定在我的主要UIViewController视图(self.view)的底部,当用户点击它时,这个函数被调用(通过UIKeyboardWillShowNotification),这将改变高度self.view.frame:

-(void)keyboardWillShow: (NSNotification*) notification {
    NSDictionary* info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGFloat textFieldHeight = activeField.frame.size.height;
    CGPoint textFieldOrigin = activeField.frame.origin;
    textFieldOrigin.y += textFieldHeight;

    CGRect visibleRect = self.view.frame;
    visibleRect.size.height -= keyboardSize.height;

    if (!CGRectContainsPoint(visibleRect, textFieldOrigin)) {
        CGRect r = self.view.frame;
        r.size.height -= keyboardSize.height;

        [UIView animateWithDuration:1.0
                     animations:^{
                         self.view.frame = r;
                     }];
    }
}

它调整了self.view.frame的大小,所以它全部被调用并运行,但由于某种原因拒绝在一秒钟内制作动画 - 它只是立即出现。

为了动画这个高度变化,我需要做些什么?

2 个答案:

答案 0 :(得分:1)

尝试稍微延迟发送,例如:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  [UIView animateWithDuration:1.0
                     animations:^{
                         self.view.frame = r;
                     }];
}

通常会成功。

答案 1 :(得分:1)

如果你有自动布局,你不应该直接改变框架,而应该改变约束。 将IBOutlet添加到约束(底部约束),并像这样更改常量:

myTextFieldConstrain.constant -= YOUR_VALUE

此外,如果您想要设置动画,请在更改常量后调用[YOURSUPERVIEW layoutIfNeeded];

示例:

[UIView animateWithDuration:1.0
                     animations:^{
                         myTextFieldConstrain.constant -= YOUR_VALUE;
                         [YOURSUPERVIEW layoutIfNeeded];
                     }];