AlexHsieh
AlexHsieh

Reputation: 123

iOS - UILabel created in storyboard doesn't animate correctly

I dragged a UILabel named testLabel into storyboard at position A(140,40). I'd like to animate it from A to position B(100,250). So I wrote the code as following..

#import "testViewController.h"

@interface testViewController ()
@property (weak, nonatomic) IBOutlet UILabel *testLabel;
@end

@implementation testViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [UIView animateWithDuration:1.0
                          delay:1.0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         CGPoint b = CGPointMake(100, 250);
                         self.testLabel.center = b;
                     }
                     completion:nil];
}

@end

instead of animating from A to B, the simulator animating the label from point(0,0) to point A. Where did I get wrong?

Upvotes: 2

Views: 361

Answers (2)

Rob
Rob

Reputation: 437432

Like PaReeOhNos said, you could defer this until viewDidAppear by which point testLabel will have its starting coordinates set, or you can just do the following:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.testLabel.center = CGPointMake(140, 40);

    [UIView animateWithDuration:1.0
                          delay:1.0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         self.testLabel.center = CGPointMake(100, 250);
                     }
                     completion:nil];
}

Upvotes: 0

PaReeOhNos
PaReeOhNos

Reputation: 4398

I wouldn't do your animations in the viewDidLoad method. At this point, iOS hasn't fully calculated the frame for your subviews.

If you do this animation in a method such as viewDidAppear: what do you get happening then?

Upvotes: 1

Related Questions