Question

I've got a view controller in Storyboard that has a bunch of images, labels and buttons correctly positioned for how the view is supposed to look after initial animations.

Is there a simple way to save the original position of each and every element (that is to say the position that they're in on the Storyboard) on init so that it's possible to take those elements, move them out of view and animate them to the Storyboard layout / positions?

Was it helpful?

Solution

Yes this can be done by saving all the view's constraints in an array, then removing them, and replacing them with the new off-screen constraints (the example I have will only work if you want to move everything in self.view -- if you only want to move some of the views, then you need to loop through all of self.view's constraints, and add only those that pertain to the views you want to move to this array). When you want to move the views to their storyboard defined positions, remove the current ones, re-add the saved ones, and call layoutIfNeeded in an animation block.

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *bottomButton;
@property (weak, nonatomic) IBOutlet UIButton *topButton;
@property (weak, nonatomic) IBOutlet UIButton *middleButton;
@property (strong,nonatomic) NSArray *finalConstraints;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *viewsDict = NSDictionaryOfVariableBindings(_bottomButton,_topButton,_middleButton);
    self.finalConstraints = self.view.constraints; // save the storyboard constraints
    [self.view removeConstraints:self.view.constraints]; // remove all the storyboard constraints
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_topButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_topButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_middleButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_middleButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_bottomButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_bottomButton]-(-30)-|" options:0 metrics:nil views:viewsDict]];

    [self performSelector:@selector(moveToFinalPositions) withObject:nil afterDelay:2];
}

- (void)moveToFinalPositions {
    [self.view removeConstraints:self.view.constraints];
    [self.view addConstraints:self.finalConstraints];
    [UIView animateWithDuration:2 animations:^{
        [self.view layoutIfNeeded];
    }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top