Alex Stone
Alex Stone

Reputation: 47328

iOS7 Storyboard how to specify constraints to center a view for both landscape and portrait?

I'm trying to center a UIView using a storyboard for both landscape and portrait orientation. Below is an old springs/struts that were working for this purpose. Also below are constraints I have defined. My view does not appear centered in landscape mode. What constraint am I missing to center a view for both landscape and portrait mode?

Autoresize

enter image description here

Upvotes: 1

Views: 148

Answers (2)

Yatheesha
Yatheesha

Reputation: 10432

Add constraints for the view(View1) to align horizontally and vertically centre to its superView, and also add width and height constraints for view(View1) and create outlet for width and height constraints added.

enter image description here

@interface

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *widthConstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;

@end

Updating Constraints:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) 
{ 
    self.widthConstraint.constant = ???; //calculated Values
    self.heightConstraint.constant = ????  ;
}
else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) 
{
    self.widthConstraint.constant = ???;
    self.heightConstraint.constant = ????;
}

 [self.view layoutIfNeeeded];
}

Upvotes: 1

Fabio
Fabio

Reputation: 3067

you could associate a property with the constraints and change their value when the orientation is changed

@interface
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *leftMarginConstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *topMarginConstraint;
@end


@implementation

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) 
{ 
    leftMarginConstraint.constant = ???
    topMarginConstraint.constant = ????  
}
else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) 
{
   leftMarginConstraint.constant = ???
    topMarginConstraint.constant = ????  
}

}

Upvotes: 0

Related Questions