In my app I want to achieve this layout:
So parent view contains two sub views. First one ends exactly in a middle (height / 2) and second starts in a middle of parent view. I have found out that it is impossible to do that in the IB with constraints. So I used this code in viewDidLoad method:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:firstView
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0];
[self.view addConstraint:constraint];
Now it works but only if the app runs on the iPhone. Because size of the view is like iPhone screen. If this app runs on the iPad, there is a problem because screen has different size so this parent view is longer. And constraint (code above) still takes 0.5 * size of the views size from the IB and not size from the iPad size of the view. Item toItem:self.view still takes size from the IB.
Result is that this view has a same size in the iPad as in the iPhone. In the iPad there is a large blank space and then there is a view with iPhone size.
Can you tell what I have to do to make it universal for various screen sizes? Thank you very much
This is possible using constraints, but it is made a bit fiddly by IBs rather annoying and inflexible constraint manager. Here is how I managed it:
In IB, set the two views with the correct frames
Add an equal height constraint between the two views
Reduce the priority of any default height constraints on either of the views. Unfortunately IB does not let you remove these entirely, but setting them to anything less than 1000 will make sure they are ignored.
In the view controllers viewDidLoad method, add the constraint you already tried.
eg
- (void)viewDidLoad
{
[super viewDidLoad];
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.topView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0];
[self.view addConstraint:constraint];
}
Thats it. Screengrabs of the IB constraints are shown below:
Try this code . It will set constraint value dynamically
In your .h file , implement this lines.
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *TopsubviewheightConstraint;
Now create this constraint's as per given screen shot
connect TopsubviewheightConstraint height constraint from screen
implement this code in .m file
if (IS_IPHONE_5)
_TopSuperViewConstraint.constant = 275;
else if(IS_IPAD)
_TopSuperViewConstraint.constant = 502;
else
_TopSuperViewConstraint.constant = 230;
I hope it will help you.
you have 2 options.
create a second IB file for iPad
do everything by programm and use [[UIScreen mainScreen] bound]; instead of getting the sizes of parent ;)
I would do it without the constraints at all and set as follow:
// self.view is my container view
CGRect frame = [[UIScreen mainScreen] bound];
frame.size.height /= 2;
// upper View
upperView.frame = frame;
// lower View
frame.origin.y = frame.size.height;
// or alternatively
//frame.origin.y = CGRectGetMaxY(frame);
lowerView.frame = frame;
here you don't need any device specific options, everything is dynamic, bound to the size of your device's screen ;)
OK so I just figured out how to do this. Simply put the code into viewDidLayoutSubviews method and not to viewDidLoad. The solution I found in the topic Unable to set frame correctly before viewDidAppear.
Here is my code:
[subView1 setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2)];
[subView2 setFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, self.view.frame.size.height / 2)];
Thanks to all for effort!
Thanks to Tark's answer, I managed to to this using constraints as well:
Add Vertical Space constraint for TobView to Top Layout Guide (Using StoryBoard)
Add Vertical Space constraint for BottomView to Bottom Layout Guide (Using StoryBoard)
Add two height constraints for each view in ViewDidLoad
Code:
NSLayoutConstraint *constraint;
constraint = [NSLayoutConstraint constraintWithItem:_viewTop
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:_viewBottom
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0];
[self.view addConstraint:constraint];
You can do this with constrains (no code required!)
1.- First create two UIview and manually set it's height to half of the size of the current device, positioning one over the other, just like this:
2.- Next you must set the constraints for each one of them like this (this will allow to the container fill the whole screen, one over the another):
Top container
Bottom container
3.- Finally you must select both containers and add a new constrain that specify that they will have in the same height
(remember to clid "Add X Constrains" for each step)
now it should be ready to put the label inside each container, and you will ready
Related
Here is my problem, I have a scroll view scrollExerciseIndex that I use only as a scrolling bar, in this scroll view I place a UIView indexesView and I want it to be always at the center of the scroll view. For this I use layout constraints :
UIView * indexesView = [[UIView alloc] initWithFrame: CGRectMake(xPosition, 0, dimension*numberIndexes, dimension)];
[self.scrollExerciseIndex addSubview:indexesView];
[self.scrollExerciseIndex setContentSize:CGSizeMake(dimension*numberIndexes, dimension)];
if (xPosition != 0) {
NSLayoutConstraint * xCenterConstraint = [NSLayoutConstraint constraintWithItem:indexesView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.scrollExerciseIndex attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[self.scrollExerciseIndex addConstraint:xCenterConstraint];
}
Here is the expected result :
Don't pay attention to all the element, just the bar at the bottom of the screen is my problem.
I have to create view programmatically because sometimes I will activate the constraints, sometimes not and I have to set the frame of the view dynamically. So for now I initialise the view indexesView like so :
UIView * indexesView = [[UIView alloc] initWithFrame: CGRectMake(xPosition, 0, dimension*numberIndexes, dimension)];
(I know, not very original)
I would like to know if there is a way to initialize the view programmatically but to say to auto-layout that it has no constraints on the position because right now if the screen turns in landscape mode there is a conflict as the scrollview's frame changes so the distance between the center of the scroll view (on which I set a constraint) and the position of the subview's frame (xPosition) is no longer the same.
As you can see, the view is no longer at the center of the scroll view and I have some constraints broken.
Will attempt to recover by breaking constraint
NSLayoutConstraint:0x7bed6c50 UIView:0x7bed6ad0.centerX == UIScrollView:0x7e273200.centerX
Thanks for your help.
Ok, I found what I was looking for by reading a book about Audio-Layout.
My problem was that audio layout would create constraints behind my back automatically. When using AutoLayout a type of constraints is created from non-autoLayout specifications (The used to describe interface when auto layout didn't exist). So constraints are created using the initial frame of the view. The only thing I had to do was :
[indexesView setTranslatesAutoresizingMaskIntoConstraints:NO];
to disable this creation of constraints from the frame, and then recreate explicitly the constraints for width and height if needed (which wasn't the case for me, but I still made the test) like so :
`NSLayoutConstraint * widthConstraint = [NSLayoutConstraint constraintWithItem:indexesView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:widthValue];
NSLayoutConstraint * heightConstraint = [NSLayoutConstraint constraintWithItem:indexesView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:heightValue];
[indexesView addConstraint: heightConstraint];
[indexesView addConstraint: widthConstraint];`
When adding constraints programmatically, don't forget to call : [indexesView setNeedsUpdateConstraints]; so the constraints are recalculated only when needed.
Last info that I read and can be useful in general, when adding a lot of constraints, the apple doc specifies that it is more efficient to use the method :
[myView addConstraints:(NSArray<NSLayoutConstraints *> *)] than to call addConstraint: for each constraint.
Hope it can be useful to someone.
I am new to Auto layout constraints. I have 2 views(topView and paintView) on my main view, along with a button on the top right corner of the main view. On loading the view, the topView occupies the whole main view(excluding the button). On click of the button, I want the topView to occupy 70% of the main view and the paintView to occupy the rest(excluding the button).
I have set up the the X, Y and top constraints for the topView using storyboard. The paintView and the corresponding constraints have been set up programmatically.
The code I have now is this:
-(void)setupPaintView
{
UIView *pPaintView = [UIView new];
[pPaintView setBackgroundColor:[UIColor yellowColor]];
pPaintView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:pPaintView];
self.paintView = pPaintView;
[self addConstraintsToView];
//[self setTopViewFrame];
}
-(void)addConstraintsToView
{
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.paintView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.topView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:self.paintView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.topView
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:self.topView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.paintView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0]];
NSLayoutConstraint *pHeightConstraintTopView = [NSLayoutConstraint
constraintWithItem:self.topView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0.0];
self.heightconstraintTopView = pHeightConstraintTopView;
[self.view addConstraint:pHeightConstraintTopView];
NSLayoutConstraint *pHeightConstraintPaintView = [NSLayoutConstraint
constraintWithItem:self.paintView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.0
constant:0.0];
self.heightconstraintPaintView = pHeightConstraintPaintView;
[self.view addConstraint:pHeightConstraintPaintView];
}
On button click the following method gets called:
-(IBAction)detailBtnClick:(id)sender
{
if(self.heightconstraintPaintView.constant == 0)
{
self.heightconstraintTopView.constant = 0.7*self.view.frame.size.height;
self.heightconstraintPaintView.constant = 0.3*self.view.frame.size.height;
[self.view setNeedsUpdateConstraints];
}
else
{
self.heightconstraintTopView.constant = self.view.frame.size.height;
self.heightconstraintPaintView.constant = 0;
[self.view setNeedsUpdateConstraints];
}
}
When the view loads, the topView acquires the main view's height, which is desired here. But when I click on the button, the topView remains at 100% i.e. it does not resize and neither does the paintView. I am modifying the constant property of the topView and the paintView constraints, but I am not sure that is the correct way to go about it. The constraint here is that the views have to be laid out using Autolayout constraints only. How can I get the views to resize at the click of the button?
Any help is welcome.
Thanks to timothykc and others, I have successfully navigated the problem stated above. But I am facing another issue now.When I change the orientation of the simulator to landscape, the paintView remains almost hidden. Following is the code (toggle is a boolean value that decides whether to stretch/shrink the views):
-(IBAction)detailBtnClick:(id)sender
{
if(self.toggle == FALSE)
{
self.topViewHeightConstraint.constant = 0.7*self.bounds.frame.size.height;
self.heightconstraintPaintView.constant = 0.3*self.bounds.frame.size.height;
//[self.view layoutIfNeeded];
}
else
{
self.topViewHeightConstraint.constant = self.view.bounds.size.height;
self.heightconstraintPaintView.constant = 0;
//[self.view layoutIfNeeded];
}
self.toggle = !self.toggle;
}
The topViewHeightConstraint has been added as a property as indicated by timothykc. This is working properly for the portrait orientation, but is not working properly for landscape, as the height of the topView does not change as desired(70%), meaning that the ratios are not getting handled properly.
I'm going to provide a storyboard driven solution that should help you with other autolayout problems down the road.
My solution to your specific problem, you've got two views (1 and 2 in diagram below):
For view 1, pin the view to the left, top, and right of the superview. Then set a height constant. (e.g. 568, the full height of an iphone 5s)
For view 2, pin it to the left, bottom, and right of the superview. Then pin it to the bottom of view 1.
Open up the assistant editor view, and here's the key trick--turn the height constraint on view 1 into a nslayoutconstraint property on your VC. You do this by locating the constraint, and then control-dragging onto the VC. (e.g.`
#property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;`
Now you can manipulate this property with an action linked to your button, such as
- (IBAction)scale:(id)sender {
self.viewHeight.constant = 397.6; //%70 of 568....
}
In my example, I change the nslayoutconstraint.CONSTANT manually to an arbitrary value.
To understand what's happening, you need to know that autolayout is a means for determining the (x coord,y coord,width, height) of any layout object. Warnings occur when xcode cannot ascertain all 4 values...
In View 1, we give a constraint for Height. X,Y, and Width are extrapolated from the distance to the superview. (if something is 0 from the left and right, then the width fills the whole screen...; if 0 from top and left, then coords must be (0,0))
In view 2, X must be 0 since distance from left is 0. width whole screen... Height and Y are extrapolated based on the height of View 1!
So when we mess with height constraint in View 1, it effects the height and Y coord of View 2!
To get constraints to update on a view you would need to call [self.view layoutIfNeeded]; instead of [self.view setNeedsUpdateConstraints]; after setting the new constant on whichever constraint(s) you would like to update.
Actually this is more of an comment about my methods, but I decided to post it as an answer because firstly, this has solved my problem and secondly, it involves some snippets of code which is hard to read in the comments section. Regarding the orientation problem mentioned in the edit, I came up with a workaround to accommodate the view reszing requirements with respect to the toggle button and with respect to orientation change. The three methods used for this purpose are:
The following method is called on the button click event.
-(IBAction)detailBtnClick:(id)sender
{
[self updateViewConstraints:self.toggle];
self.toggle = !self.toggle;
}
The following method updates the constraints.
-(void)updateViewConstraints :(BOOL)toggleValue
{
if(toggleValue == FALSE)
{
self.topViewHeightConstraint.constant = 0.7*self.view.bounds.size.height;
self.heightconstraintPaintView.constant = 0.3*self.view.bounds.size.height;
}
else
{
self.topViewHeightConstraint.constant = self.view.bounds.size.height;
self.heightconstraintPaintView.constant = 0;
}
}
The following method calls the method above to update constraints in case of orientation change:
-(void)viewWillLayoutSubviews
{
[self updateViewConstraints:!self.toggle];
}
I'm trying to make a keyboard. I have 9 buttons inside a view with: width and height <= 75. On iPhone 5 works perfectly. But the iPhone 4 buttons are stretched and the size is still 75. Could anyone help me?
The problem is that your telling the views (buttons) to have a height or width >= 75 which means you have an ambiguous layout (someone already mentioned this) - you can check for this by examining the hasAmbiguousLayout property of your view. It's likely not working on the iPhone 5 correctly either it just so happens that when you've run it autolayout has found the solution you're looking for so it appears to work. Run it enough times and eventually you'll probably get the undesired layout. Ah the joys of autolayout. Anyways one solution to this problem is to set the height and width of one button, and then tell all the other buttons to follow suite. The visual format language guide has an example of this but i'll show you what I mean.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[button1(75)[button2(==button1)[button3(==button1)]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(button1, button2, button3)]];
Then do something similar to lay them out vertically. When autolayout runs it should find the correct layout for them. The next problem comes in how you use it. If you did all this work in a subclass of UIView and then went ahead and made that views width something crazy like 400 pt wide then autolayout will break - in this case because we pinned to the left and right sides. To fix this problem I'd probably remove the the last | and not pin the right side of button3 to the right side of the superview.
The other option you have is to specify constrains using the long format. For Example
//set button1 width to 75
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:button1
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:75]];
//set button2 width == button1
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:button2
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:button1
attribute:NSLayoutAttributeWidth
multiplier:1
constant:0]];
//pin button1 to the left
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:button1
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1
constant:0]];
//pin button2 to button1
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:button2
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:button1
attribute:NSLayoutAttributeRight
multiplier:1
constant:0]];
Have you considered changing the height programmatically? Here is a stub of code I use.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
//iPad Code
}else{
if([[UIScreen mainScreen] bounds].size.height > 560){
//iPhone 5 Code
}else{
// iPhone 4 Code
}
}
First of all your basic design should be iPhone 4.
It will be much easier to increase the screen design than to shrink it.
Now, regarding your question, it depends on what you want to achieve.
(1) Do you want only the top and the bottom padding to change in different devices?
(2) Do you want the buttons to have different sizes in different devices?
(3) Do you want the spaces between the buttons to be different in different devices?
Anyway, you should set a constraints for equal width and equal height for all the buttons.
From now on, the easiest solution (1) is to put all the buttons in one container that will have a constant height and will be centered in the screen.
This way there will be lower or higher padding around the buttons on different devices.
If you want the spaces between the buttons to change (2) then you can create a matrix of views (imagine sudoku), make all the views have equal widths and heights (constraints) and zero space between them (also constraints), put a button in the center of each view (constraints).
This way the buttons will remain in the same size but the spaces between them will grow or shrink.
Let me know if you understand the above solutions.
A pretty simple question I reckon:
one UIViewController
one custom UIView
The controller only does:
-(void)loadView{
[super loadView];
self.sideMenu = [[sideMenuView alloc]init];
[self.view addSubview:self.sideMenu];
}
and in the UIView I would like to do something like:
self.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeLeading multiplier:1 constant:100];
[self.superview addConstraint:constraint];
So that when I create the UIView in the controller its constraints is already set in relation to the controller.
I have tried and nothing crashes but the UIView gets realy weird x and y coords
Maby I need to update the constraints? Or maby this isnt at all possible?
I'm not sure what ui behavior you are exactly looking for since it appears that you are trying to tie the leading space of your view to the leading space of it's superview. Being the leading space, the space on the left of the view, could it be that you are looking for the more common "stick my left side 100 pixels from my parents left border"? Anyway, in either case, I would connect an outlet from the controller to the custom view (i.e. myCustomView below) and then build the constraint in the UIViewController and not the UIView by overriding:
- (void)updateViewConstraints {
[super updateViewConstraints];
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:myCustomView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:myCustomView.superview
attribute:NSLayoutAttributeLeading
multiplier:1
constant:100];
[myCustomView addConstraint:constraint];
}
Apple has an interesting page with a table showing the various runtime entry points for autolayout at this address:
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Articles/runtime.html#//apple_ref/doc/uid/TP40010853-CH6-SW1
You might consider adding other constraints as well. Auto layout has the the tendency to exploit any freedom you leave unchecked in the worst possible way ;-)
So leading edge is not enough.
You need enough constraints to satisfy vertical and horizontal layout.
In one direction you need at least
one edge & width (or hight)
Or
Two edges ( implicit width or height )
Or
A horizontal (or vertical) center based constraint and an explicit width ( or height respectively)
The thing about width and height is that they can also be determined by intrinsic content size.
Add constraints after adding the view to the superview.
A bit late but PureLayout is pretty handy https://github.com/smileyborg/PureLayout
I'm having an issue with auto layout and constraints and could use some help.
I am running this application on an iPad. I have a window that contains two views, a UIWebView and an MKMapView. Both of those views are set up in IB, and Auto Layout is turned on. The UIWebView is positioned at the top of the window and the MKMapView is at the bottom. Each view takes up almost half of the window. The UIWebView has the following constraints set up in IB: NSLayoutAttributeTop to Superview equal to 0, Leading Edge to Superview equal to 0, Trailing Edge to Superview equal to 0, and NSLayoutAttributeBottom to Superview equal to 480. The MKMapView has the following constraints set up in IB: NSLayoutAttributeTop to Superview equal to 480, Leading Edge to Superview equal to 0, Trailing Edge to Superview equal to 0, and NSLayoutAttributeBottom to Superview equal to 0.
When the window is loaded, the MKMapView is actually removed, since I want the UIWebView to take up the entire screen, because there is no data to display in the map view. This is done in my updateDetailViews function:
- (void)updateDetailViews
{
displayHeight = self.maximumUsableFrame.size.height;
viewDistance=displayHeight/2+centerMapButton.frame.size.height/2+16;
[detailMapView setTranslatesAutoresizingMaskIntoConstraints:NO];
[directoryWebView setTranslatesAutoresizingMaskIntoConstraints:NO];
if (mapViewVisible==true) {
webViewDistFromBottomDefault=viewDistance;
webViewDistFromBottom.constant=viewDistance;
mapViewDistFromTopDefault=viewDistance;
mapViewDistFromTop.constant=viewDistance;
}
else {
[detailMapView removeFromSuperview];
webViewDistFromBottomDefault=0;
webViewDistFromBottom.constant=0;
mapViewDistFromTopDefault=viewDistance;
mapViewDistFromTop.constant=viewDistance;
}
[detailMapView setNeedsUpdateConstraints];
[UIView animateWithDuration:0.25f animations:^{
[self.detailMapView layoutIfNeeded];
}];
}
After the MKMapView is removed, the NSLayoutAttributeBottom attribute of UIWebview is set to 0, and it fills the entire screen. Once there is actual data to show in the map, the MKMapView is then added, and the UIWebView repositioned, along with the necessary constraints, in my displayMapView function:
- (void)displayMapView
{
double dblLatitude;
double dblLongitude;
[detailMapView setTranslatesAutoresizingMaskIntoConstraints:NO];
if ([self isMapViewDisplayed]==FALSE) {
[detailView addSubview:detailMapView];
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:detailMapView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:detailView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:mapViewDistFromTopDefault];
[detailView addConstraint:myConstraint];
//mapViewDistFromTop.constant = mapViewDistFromTopDefault;
myConstraint =[NSLayoutConstraint
constraintWithItem:detailMapView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:detailView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0];
[detailView addConstraint:myConstraint];
myConstraint =[NSLayoutConstraint
constraintWithItem:detailMapView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:detailView
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:0];
[detailView addConstraint:myConstraint];
myConstraint =[NSLayoutConstraint
constraintWithItem:detailMapView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:detailView
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:0];
[detailView addConstraint:myConstraint];
[detailMapView setNeedsUpdateConstraints];
}
[UIView animateWithDuration:.5
animations:^{
webViewDistFromBottom.constant=webViewDistFromBottomDefault;
mapViewDistFromTop.constant=mapViewDistFromTopDefault;
[self.directoryWebView layoutIfNeeded];
[self.detailMapView layoutIfNeeded];
}];
[self updateDetailViews];
...
if ((dblLatitude != 0) && (dblLongitude != 0)) {
zoomLocation.latitude = dblLatitude;
zoomLocation.longitude = dblLongitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, METERS_PER_MILE, METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [detailMapView regionThatFits:viewRegion];
[detailMapView setRegion:adjustedRegion animated:YES];
}
CLLocationCoordinate2D coordinate;
coordinate.latitude = dblLatitude;
coordinate.longitude = dblLongitude;
...
[detailMapView addAnnotation:annotation];
}
All of this works like I intend. The problem occurs when the device is rotated. If I start with the iPad in portrait mode, the webViewDistFromBottom and mapViewDistFromTop constraints are set to 490, due to the updateDetailViews function above which has the following calculations:
displayHeight = self.maximumUsableFrame.size.height;
viewDistance=displayHeight/2+centerMapButton.frame.size.height/2+16;
If the iPad is rotated to landscape, the willAnimateRotationToInterfaceOrientation function is called, which then calls updateDetailViews, which sets viewDistance to 367 (and correspondingly webViewDistFromBottom.constant and mapViewDistFromTop.constant). The UIWebView on top looks as it should, however, the MKMapView on bottom does not. The mapViewDistFromTop constraint is set to 367 (if I output the value to the log), however it appears that it is still set to 490. My updateDetailViews function calls [self.view layoutIfNeeded] (and I have also tried [detailMapView layoutIfNeeded], [detailMapView setNeedsLayout]), but that view does not show up correctly. The distance from the top is too large. If I rotate the iPad back to portrait, it looks fine.
I also have the same problem if the iPad is started in landscape mode, then rotated to portrait. In landscape mode, the mapViewDistFromTop and webViewDistFromBottom values are 367, and are set to 490 once rotated to portrait. However, the MKMapView on the bottom looks as those the distance from the top is still 367, covering too much of the display.
Any idea what I'm doing wrong? Thanks in advance for any assistance!!!
If I understand the question correctly, when in portrait you want a map view, 480 points tall, at the bottom, and if in landscape, you want the web view to take up the whole screen. An alternative approach would be to just modify the height of the map view (480 in portrait, 0 in landscape). Don't remove the map view, just set its height to 0. And let the existing constraints take care of everything else. Then there are no adding of modifying of constraints, views, etc. All you need to do is adjust one constant on rotation. Does that do the job?
To illustrate this, in this scenario I'm suggesting you set up your constraints (I'll only focus on the vertical constraints) so that they are equivalent to
V:|[webView][mapView(480)]|
(I'm not suggesting you use VFL to specify the constraints, but it's just the most concise way to articulate the series of constraints I used.) Note, make sure you don't have any extraneous constraints floating around (e.g. web view bottom constraint to super view, etc.). I'm proposing, in the vertical dimension, just these constraints (web view top to super view, web view bottom to map view top, map view height, and map view bottom to super view).
Then, define and link an outlet for the height constraint of the mapView:
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *mapViewHeightConstraint;
Finally, on rotation, just change the constant for that constraint:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation))
self.mapViewHeightConstraint.constant = 480.0;
else
self.mapViewHeightConstraint.constant = 0.0;
}
If I understand the UI you're shooting for, I think that's all you need, eliminating all of that other code in your question. I just tested it and it seems to work fine.