开发者

Code only working in ViewDidLoad method

I'm using this code after in my ViewDidLoad method :

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

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

[UIView commitAnimations];

It's working fine but if I try to do the same thing in an other method in the same implementation file like this :

- (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];



}

Then the animation doesn`t work anymore ( but the NSLog still prints ) . Why would this method behave differently than after "viewDidLoad" ? The setViewMovedUp is called after a button is pressed, therefore I assume that the view is already loaded ? Should I add a condition to make sure that the view is loaded then ?


Edit after Michal's comment :

The button 开发者_C百科I press uses this IBAction in MyViewController.m :

- (IBAction)viewUp {

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

}

and this is the code in 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];



}

The Button's IBAction is not communicating well with the MainViewController method (setViewMovedUp) .

In you example it's working well in the same class .


You animate different views, self.containerView in first case, self.view in second.

Answer after Julz's edit:

Now it's clear what you're doing wrong. You can't call animations on an object that you just created because it's not on screen yet. You need to execute the animation code later (at least in the next loop's execution), usually with performSelector:withObject:afterDelay or blocks.

For example like this:

- (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];

This doesn't work because moveup.view will not be valid until... guess what, after its viewDidLoad is called. (or more specifically, loadView)

Using performSelector:withObject:afterDelay: might work, but it's really more like a hack.

If you want the animation to happen right after the view is shown, you really should put it in viewDidLoad, viewWillAppear, or viewDidAppear. Do you mind sharing the reason why you don't want to do that in viewDidLoad?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜