为啥移动 UIView 不会在同一个视图上移动 UIImageView?

Posted

技术标签:

【中文标题】为啥移动 UIView 不会在同一个视图上移动 UIImageView?【英文标题】:Why moving UIView is not moving UIImageView on same view?为什么移动 UIView 不会在同一个视图上移动 UIImageView? 【发布时间】:2016-04-04 00:02:12 【问题描述】:

我在 UIView 上有一个 ImageView。我正在尝试移动视图键盘大小,但所有内容都正确移动,而不是 UIImageView。

-(void) keyboardWillShow:(NSNotification *) notification 
    NSDictionary* keyboardInfo = [notification userInfo];

    // Work out where the keyboard will be
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];

    // Work out animation duration
    NSTimeInterval animationDuration =[[keyboardInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    UIViewAnimationOptions keyboardAnimationCurve = [[keyboardInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];


    // Animate this
    [UIView animateWithDuration:animationDuration
                          delay:0.0
                        options:keyboardAnimationCurve
                     animations:^()
                         self.view.frame = CGRectOffset(self.view.frame, 0, -keyboardFrameBeginRect.size.height);
                     
                     completion:NULL];


    [UIImageView animateWithDuration:animationDuration
                          delay:0.0
                        options:keyboardAnimationCurve
                     animations:^()
                         self.imgBankLogo.frame = CGRectOffset(self.imgBankLogo.frame, 0, -keyboardFrameBeginRect.size.height);
                     
                     completion:NULL];

有人有同样的问题或建议吗?我什至试图移动 UIImage 但它没有移动。

你可以看到除了 imageview 之外的所有东西都移动了!

【问题讨论】:

【参考方案1】:

如果您尝试将两个视图一起移动,其中一个是另一个的子视图,则不需要单独为它们设置动画。

动画父视图应该自动移动所有子视图。在我的经验中,尝试同时单独为它们设置动画可能会导致奇怪的结果。这个动画块应该是你所需要的。您可能还想检查视图文件检查器选项卡中的自动布局设置。

如果您想一次执行多个动画,您也可以在同一个动画块中添加多个调用。

[UIView animateWithDuration:animationDuration
                      delay:0.0
                    options:keyboardAnimationCurve
                 animations:^()
                    //you can add multiple here
                     self.view.frame = CGRectOffset(self.view.frame, 0, -keyboardFrameBeginRect.size.height);
                 
                 completion:NULL];

【讨论】:

首先我只做了一个动画作为你的答案,但是移动父视图并没有移动子视图然后我尝试了那个! 只需在主视图中获取另一个视图并尝试编辑该框架。并且也不要尝试编辑主视图的框架,即 self.view 可能会导致问题

以上是关于为啥移动 UIView 不会在同一个视图上移动 UIImageView?的主要内容,如果未能解决你的问题,请参考以下文章

UIView 在其 Superview 内移动

如何将子层与 UIView 一起移动?

在更改其嵌套的 UILabel 时移动 UIView 会导致视图跳回初始位置

为啥使用 UIPanGestureRecognizer 移动对象时会有延迟?

移动带有子视图的 UIView

使用 UIPanGestureRecognizer 缩放和移动 UIView