DarthCaniac
DarthCaniac

Reputation: 383

iOS dynamically moved images won't stay put

I am writing an app for iPhone, which upon loading, moves a few UIImages to specific places on the screen. When the app first comes up, everything is where I want it. But if I show a modal page, as that page is transitioning in, the images "pop back" to their old places for a split second while the page comes up. (Even if I call the image moving code again in the same event). Then when I dismiss the modal page, the images won't move at all, even though it does show my image mover event runs in the log. Here is my code:

-(void)ajustScreen
{
NSLog(@"Move Images");
self.imageA.frame = CGRectMake(0, 0, 80, 80);
self.imageB.frame = CGRectMake(0, 0, 80, 80);
self.imageA.center = CGPointMake(100, 100);
self.imageB.center = CGPointMake(180, 180);
}

I have this code here:

[self performSelector:@selector(ajustScreen) withObject:nil afterDelay:0.0];

fired off when the screen rotates, in viewWillAppear, viewWillDisappear, viewDidLoad, and then in an NSNotificationCenter that is supposed to call it when a modal is dismissed.

-(void)sendToAbout
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ajustScreen) name:@"SecondViewControllerDismissed" object:nil];
[self performSegueWithIdentifier: @"goabout" sender: self];
}

(And in the modal):

- (IBAction)BackButton:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"SecondViewControllerDismissed"
                                                    object:nil
                                                  userInfo:nil];
[self.navigationController dismissViewControllerAnimated:YES completion:NULL];
}

What confuses me is that there are no errors, and each time, the log prints out that it was run, but it doesn't consistently work.

Upvotes: 1

Views: 140

Answers (1)

Corey
Corey

Reputation: 5818

Try to use the UIViewController method viewDidLayoutSubviews. Something like:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.imageA.frame = CGRectMake(0, 0, 80, 80);
    self.imageB.frame = CGRectMake(0, 0, 80, 80);
    self.imageA.center = CGPointMake(100, 100);
    self.imageB.center = CGPointMake(180, 180);
}

On a side note:
Rather than using Notification Center to notify the closing of the modal and allowing the modal to dismiss itself, it's better practice to create a protocol for the modal. Then set your view controller as the delegate and dismiss the modal controller from a delegate method.

It certainly will work the way you have it, but it forces you to use the notification center. Plus, if you use the completion block, you don't run the risk of having your object removed from memory before the block completes it's process.

Upvotes: 1

Related Questions