繁体   English   中英

代码仅适用于ViewDidLoad方法

[英]Code only working in ViewDidLoad method

我在ViewDidLoad方法中使用以下代码:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.5];

self.view.frame = CGRectMake(0, 0, 250, 50);

[UIView commitAnimations];

它工作正常,但是如果我尝试在同一实现文件中的其他方法中执行相同的操作,如下所示:

- (void)setViewMovedUp:(BOOL)movedUp {


            NSLog(@"test movedUp ");
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:.5];

            self.view.frame = CGRectMake(0, 0, 250, 50);

            [UIView commitAnimations];



}

然后动画不再起作用了(但是NSLog仍然可以打印)。 为什么此方法的行为与在“ viewDidLoad ”之后不同? 按下按钮后将调用setViewMovedUp ,因此我认为视图已加载? 我是否应该添加条件以确保随后加载了视图?


在Michal评论后编辑

我按下的按钮在MyViewController.m中使用了IBAction:

- (IBAction)viewUp {

    MainViewController *moveUp = [[MainViewController alloc] init];
    [moveUp setViewMovedUp:YES];

}

这是MainViewController.m中的代码:

- (void)setViewMovedUp:(BOOL)movedUp {



    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    self.view.frame = CGRectMake(0, 0, 250, 250);
    [UIView commitAnimations];



}

Button的IBAction与MainViewController方法(setViewMovedUp)不能很好地通信。

在您的示例中,它在同一个类中运行良好。

您可以为不同的视图设置动画,第一种情况是self.containerView,第二种情况是self.view。

在Julz编辑后回答:

现在很清楚您在做什么错。 您无法在刚刚创建的对象上调用动画,因为它尚未出现在屏幕上。 您需要稍后(至少在下一个循环的执行中)执行动画代码,通常使用performSelector:withObject:afterDelay或块。

例如这样:

- (void)setViewMovedUp:(BOOL)movedUp {
    [self performSelector:@selector(animateViewUp:) withObject:nil afterDelay:0.0];
}

- (void)animateViewUp:(id)o {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    self.view.frame = CGRectMake(0, 0, 250, 250);
    [UIView commitAnimations];
}
MainViewController *moveUp = [[MainViewController alloc] init];
[moveUp setViewMovedUp:YES];

这是行不通的,因为moveup.view直到...猜测其viewDidLoad被调用之后才有效。 (或更具体地说, loadView

使用performSelector:withObject:afterDelay:可能有效,但实际上更像是黑客。

如果您希望动画在显示视图之后立即发生,那么您确实应该将其放在viewDidLoadviewWillAppearviewDidAppear 您介意分享不想在viewDidLoad这样做的原因吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM