OGeek|极客世界-中国程序员成长平台

标题: 带有 ViewWillLayoutSubview 的 IOS 动画 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:35
标题: 带有 ViewWillLayoutSubview 的 IOS 动画

我的 viewController 中有这个动画可以缩小并向下滑动我的菜单。

-(void)dismissMenuWithAnimation
{
    CGRect originalFrame = self.view.frame;
    [UIView animateWithDuration:2
                     animations:^{
                         self.view.frame = CGRectMake(originalFrame.origin.x,originalFrame.origin.y+originalFrame.size.height,originalFrame.size.width,10);
                     }
                     completion:^(BOOL finished){
                         [self.view removeFromSuperview];
                         self.view.frame = originalFrame;
                     }];
}

在同一个 viewController 中,我将覆盖 viewWillLayoutSubviews:

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    CGRect viewBounds = self.view.bounds;
    self.subView1.frame = CGRectMake(self.menuItemMidPosition,viewBounds.size.height-SUBVIEW1_HEIGHT,SUBVIEW1_WIDTH,SUBVIEW1_HEIGHT);

}

我有几个 subview 的框架是在这个 viewWillLayoutSubviews 方法中设置的。没有在 viewDidLoad 中设置它,因为那时框架仍然不正确。

问题是,当我关闭菜单时,首先调用动画 block ,并且不知何故 self.view.frame 立即设置为高度 10。(缩小的帧)。当它到达 viewWillLayoutSubviews 时,边界高度为 10。这导致我的其他 subview 显示不正确。

这似乎很愚蠢,但我不知道如何解决这个问题。有人可以帮忙吗?谢谢。



Best Answer-推荐答案


我遇到了和作者一样的问题。虽然这个问题很老,但我会发布我的解决方案,希望有人会像我一样碰到这个问题。

解决方案非常简单,完全类似于基于自动布局的动画:

UIView.animate(
  withDuration: 0.2,
  delay: 0,
  options: .curveEaseInOut,
  animations: {
    // This will launch viewWillLayoutSubviews!
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
},
  completion: nil)

和 Objective-C 版本:

[UIView animateWithDuration:0.2
                    delay:0
                  options:UIViewAnimationOptionCurveEaseInOut
               animations:^{
                 // This will launch viewWillLayoutSubviews!
                 [self.view setNeedsLayout];
                 [self.view layoutIfNeeded];
               }
               completion:nil];

我喜欢完全程序化的布局,尽管我们在 2017 年有了自动布局引擎。

关于带有 ViewWillLayoutSubview 的 IOS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13132321/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4