Here we see an example of how to move an entire UIView with auto layout.
The idea here is to:
- Create a UIView
- Add some controls to it
- Make something happen.
- And then move the entire view by adjusting the value of a constraint.
First create a new single page application and drag a UIView onto it.
Give it a background colour of green. Stretch it out so it locks to the sides of the parent view.
Then add have autolayout automatically add some constraints to it by clicking
This will automatically add the necessary constrains for us. Including the top one which we want to manipulate.
Then drag the top constraint over as an outlet, and add two buttons to reset it’s size programatically.
The buttons are going to reside inside our new UIView
We are going to slide the whole view up/down by pressing the buttons and manipulating the value of the top constraints.
Add constraints to the Up/Down buttons so they stay embedded in the UIView like so
Your constraints should now look like this.
Now the fun part. Add code to slide the entire UIView up and down.
Do this by adding actions for the up/down buttons and the following code.
If you want to get fancy you can add an animation like in the down button.
All the code and everything should eventually look like this.
#import "ViewController.h" @interface ViewController () @property (strong, nonatomic) IBOutlet UIView *baseView; @property (strong, nonatomic) IBOutlet NSLayoutConstraint *topConstraint; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CGRect newFrame = self.baseView.frame; newFrame.size.width = [[UIScreen mainScreen] bounds].size.width; newFrame.size.height = [[UIScreen mainScreen] bounds].size.height; [self.baseView setFrame:newFrame]; self.baseView.userInteractionEnabled = YES; } - (IBAction)upPressed:(UIButton *)sender { NSLog(@"Up pressed"); self.topConstraint.constant = 0; [self.view layoutIfNeeded]; } - (IBAction)downPressed:(UIButton *)sender { NSLog(@"Down pressed"); [UIView animateWithDuration:0.5 animations:^{ self.topConstraint.constant = 100; [self.view layoutIfNeeded]; }]; } @end
And when you run it and press the up/down buttons, the whole thing should like up/down.