BobC
BobC

Reputation: 655

UIView animation doesn't work first time

I have a seachButton in the navigation bar which upon hitting calls following method:

- (IBAction)search:(id)sender
{
if (nil == searchViewController)
    searchViewController = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil];

searchViewController.view.backgroundColor = [UIColor clearColor];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown
                       forView:searchViewController.view
                         cache:NO];

[self.view addSubview:searchViewController.view];
[UIView commitAnimations];
}

It should load SearchViewController.xib which contains a view with UISearchBar and two buttons. When I call the search method for the first time, the view appears very quickly with some weird animation, when I call it again, the animation is alright. Does anyone have a clue what could be wrong?

Upvotes: 0

Views: 2141

Answers (4)

AJJ
AJJ

Reputation: 31

Try putting the code for animations and view loading in the viewDidAppear: method instead of viewDidLoad: (which Chris suggested above).

In general, I have had problems doing view related things in viewDidLoad:. But doing those in viewDidAppear: has always helped (I might be missing some subtlety that causes this behavior).

Upvotes: 0

Rene
Rene

Reputation: 11

Add both views to window in appdelegate, I had the same problem you had and this worked. Strange because later on I remove them from the superview but it is still working.

Upvotes: 1

chris
chris

Reputation: 184

Try putting the animation code in the viewDidLoad function. This ensures all assets and views from the nib file have been loaded and are able to be used by your app.

- (IBAction)search:(id)sender
{
if (nil == searchViewController)
    searchViewController = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil];

[self.view addSubview:searchViewController.view];
}

-(void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor]; 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:1.0]; 
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown 
                   forView:self.view 
                     cache:NO];
[UIView commitAnimations];
}

Upvotes: 0

zonble
zonble

Reputation: 4213

A UIViewController does not load its view until the view method is called. I guess the problem is the view is not loaded when you call the animation first time. You can try to modify you code like this:

if (nil == searchViewController) {
    searchViewController = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil];
    searchViewController.view;
}

Upvotes: 0

Related Questions