Reputation: 47328
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?
Upvotes: 1
Views: 148
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.
@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
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