Animating the state / position of the storyboard

I have a view manager in a Storyboard that has a bunch of images, labels and buttons correctly positioned for how the view is supposed to look after .

Is there an easy way to store the original position of each element (i.e. the position they are on the storyboard) in init so that we can take those elements, take them out of view, and animate them to the storyboard's layout / positions?

+1


source to share


1 answer


Yes, this can be done by keeping all view constraints in the array, then removing them and replacing them with new outer constraints (the example I'm using will only work if you want to move everything in self.view - if you only want move some of the views, then you need to skip all the constraints of self.view and only add the ones related to the views you want to move to that array). If you want to move the views to your foldout frames, then delete the current ones, re-add the saved ones and call layoutIfNeeded in the 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];
    }];
}

      

+1


source







All Articles