iOS Autolayout same width constraint - ios

I've got a layout which I want to look like this:
Location: "blabla"
Website: "blabla"
LongerLabel: "blabla"
I want all the labels to be the same width. Hardcoded this can look like this:
#"H:|[locationLabel(80)]-5-[location]|"
#"H:|[websiteLabel(80)]-5-[website]|"
#"H:|[remarksLabel(80)]-5-[remarks]|"
I've already tried this using circular reference which doesn't work ;)
#"H:|[locationLabel(websiteLabel)]-5-[location]|"
#"H:|[websiteLabel(remarksLabel)]-5-[website]|"
#"H:|[remarksLabel(locationLabel)]-5-[remarks]|"
I do not want my labels to be hardcoded to 80, but I want them all the same width according to the max intrinsic content size.

You can do it using circular greater-than-or-equal-width constraints:
#"H:|[locationLabel(>=websiteLabel)]-5-[location]|"
#"H:|[websiteLabel(>=remarksLabel)]-5-[website]|"
#"H:|[remarksLabel(>=locationLabel)]-5-[remarks]|"
(sorry for weird colors :) )
UPDATE: I've just checked simple "equal" circular constraints, and they work in my case as well. However, I think, "equal" constraints don't specify the "main" label in any way, they just state, that labels should be equal. And if they are all equal to the smallest label, it is also fine. So in the "equal" case it probably depends on the order of constraints.
Now let's take a look at two hypothetical labels ("Label" and "Label label" (LL for shortness)), which are connected using ">=" constraints.
Warning: the following text is just an assumption, I've never seen an actual autolayout implementation. I just know that it uses a complicated linear equations solving system to find a solution which satisfies all constraints as close as possible.
The autolayout engine (AE) takes the first label and makes it as small as possible because of the content hugging. The LL is ignored for now. Then the AE takes the second label. In case of equal constraints it would have to make it short, like the first labels, because the first label has already been processed. But in case of ">=" constraint the AE can make the second label longer. However, now it affects the "L >= LL" constraint and AE has to switch back to L and process it one more time using the new data (in case of "==" constraint it would stop already, because no conflicts emerged). The only solution now is to make the first label longer, which AE does, because it doesn't introduce any conflicts.
So, this way in several iterations the AE ends up with all labels being the same width (the width of the longest label).

Yes, you can specify fix-same width constraints using Visual Formatting language.
Constraints will be like below:
#"H:|[locationLabel]-5-[location]|"
#"H:|[websiteLabel]-5-[website]|"
#"H:|[remarksLabel]-5-[remarks]|"
Below additional constraints are required:
// Width constraints for Left side labels
NSLayoutConstraint *locationLabelConstraint = [NSLayoutConstraint constraintWithItem:locationLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.6 constant:0];
[self.view addConstraint:locationLabelConstraint];
NSLayoutConstraint *websiteLabelConstraint = [NSLayoutConstraint constraintWithItem:locationLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.6 constant:0];
[self.view addConstraint:locationLabelConstraint];
NSLayoutConstraint *remarksLabelConstraint = [NSLayoutConstraint constraintWithItem:locationLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.6 constant:0];
[self.view addConstraint:remarksLabelConstraint];
// Width constraints for right side labels
NSLayoutConstraint *locationConstraint = [NSLayoutConstraint constraintWithItem:locationLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.3 constant:0];
[self.view addConstraint:locationConstraint];
NSLayoutConstraint *websiteConstraint = [NSLayoutConstraint constraintWithItem:locationLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.3 constant:0];
[self.view addConstraint:websiteConstraint];
NSLayoutConstraint *remarksLabelConstraint = [NSLayoutConstraint constraintWithItem:locationLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.3 constant:0];
[self.view addConstraint:remarksConstraint];
Explanation:
Above all constraints are width constraints equally related to its parent view width, these means labels will take all full width of its parent view. Here you can change multiplier to fix labels width.
Multiplier = 1 => Full view width
Multiplier = 0.5 => Half view width
Observe left side label width constraint where multiplier = 0.6 which means that it will take 0.6% space of self.view width.
Same way right side label width multiplier = 0.3 which takes 0.3% space of self.view. Change these values as your convenience.
Note: Also please check Xcode console sometimes there constraints gives warnings about constraint conflict. If there is any warning please resolve by changing constraints properties.

Not sure if I am missing something, but simple 'equal width' constraints should have sufficed (no need for >=). They did for me.
The default compression resistance priority (750) is greater than the default content hugging priority (250). So it all works out in the end.

Related

detailCalloutAccessoryView constraints in MKAnnotationView

i have some problems sizing a detailCalloutAccessoryView that i added programmatically.
Here's the code for the view
HCSStarRatingView *annotationRating = [[HCSStarRatingView alloc] init];
annotationView.detailCalloutAccessoryView = annotationRating;
I tried to init the view with a initWithFrame but somehow that didn't work and i ended up with this.
I then discovered that i have to add NSLayoutConstraint programmatically to size the view correctly, so i added this code for constraints.
NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:annotationRating attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:80];
NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:annotationRating attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:45];
[annotationRating addConstraint:width];
[annotationRating addConstraint:height];
And the view now looks like this
Now i want to get rid of the white space around it. I think i have to add a top and bottom constraint but i don't know how to do it because I don't know what items i have to relate to.
The excess whitespace is a function of the height that you've chosen. Your image is roughly 5 times as wide as it is tall, but you've asked to render it in a box that 80 x 45 pts (i.e. a view whose height is over half the width, rather than one fifth). If you pick the dimensions of the image view to match (adjusting for scale) the size of the image, you get something more like:
As you can see, with judicious selection of the width and height, there will be less whitespace than in your example. Note, there is some inherent whitespace between the detail accessory view that you cannot control, but by making sure you set the width and height correctly, you can reduce it to these minimal values.

How to change aspect ratio of a UIView

I have a custom UIView which uses autolayout programatically to set the size of the frame. For this purpose, I set a constraint on the width property of the view to be equal to that of the superview and then a constraint of the aspect ratio to be some hard coded value
//width constraint
NSLayoutConstraint *widhtConstraint=[NSLayoutConstraint constraintWithItem:entryView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:scrollView
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:8.0f];
[scrollView addConstraint:widhtConstraint];
//aspect ratio constraint
NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:entryView
attribute:NSLayoutAttributeHeight
multiplier:80.0/27.0//aspect ratio same as formula view
constant:0.0f];
[scrollView addConstraint:aspectRatioConstraint];
Please refer image:
I wish to change the aspect ratio of this frame on touch of a button(View More) by increasing its height and then later resize it back to original on touching the same button.Additionally how do I figure out the total height of the view governed by all its subviews such that each subview is visible without clipping.(Basically the standard collapse feature)
You can have the aspect ratio as a variable in your code and have the code to set the constraints in a method such as updateConstraints.
float aspectRatio; NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:entryView
attribute:NSLayoutAttributeHeight
multiplier:self.aspectRatio//aspect ratio same as formula view
constant:0.0f];
Then when the button is pressed, in the action method you can modify the self.aspectRatio as fit and then call setNeedsUpdateConstraints and subsequently setNeedsLayout.
I haven't understood exactly what the question is, but changing constraints in response to a button press so as to expand / collapse a superview is easy:
If that is the kind of thing you are after, you can find a downloadable example project here: https://github.com/mattneub/Programming-iOS-Book-Examples/tree/master/bk2ch04p183animationAndAutolayout4

NSLayoutConstraints with NSLayoutAttributeTrailing not as expected

I have an array with two new constraints.
When I set these constraints the button is placed 20 and 90 pix from the center of the superview.
I want the button 20px from the bottom and 90px from the right of the superview.
What am I doing wrong?
I create an array with two constraints:
NSLayoutConstraint *bottomTrailingConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:90.0f];
NSLayoutConstraint *bottomSpaceConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeBottom
multiplier:1.0f
constant:20.0f];
_bottomConstraintsArray = #[bottomTrailingConstraint, bottomSpaceConstraint];
I remove the old constraints and then add the new constraints:
NSArray *oldconstraints = _gameSettingsButton.constraints;
[_gameSettingsButton.superview removeConstraints: oldconstraints];
[_gameSettingsButton.superview addConstraints:_bottomConstraintsArray];
I also tried: [_gameSettingsButton.superview updateConstraints] but that changes nothing.
Any help would be greatly appreciated.
This:
NSLayoutConstraint *bottomTrailingConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:90.0f];
means:
_gameSettingsButton.trailing == _gameSettingsButton.superview.trailing * 1 + 90
That will make the button's trailing edge outside of the superview. Assuming left-to-right layout (so "trailing" means "right"), the button's right edge will be 90 points to the right of the superview.
Similarly, this:
NSLayoutConstraint *bottomSpaceConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeBottom
multiplier:1.0f
constant:20.0f];
means:
_gameSettingsButton.bottom == _gameSettingsButton.superview.bottom * 1 + 20
Again, this will put the button outside of the superview. The button's bottom edge will be down 20 points from the bottom of the superview.
You either want to swap the first and second items or you want to negate the constant.
Also, you are querying the constraints from the button and then removing those constraints from the superview. Well, since the constraints you queried are not on the superview, that does nothing. (In fact, the result of your query is probably an empty array since nothing ever adds any constraints to the button itself.) You probably meant to query the constraints on the superview but I suspect there will be constraints unrelated to the button which you don't want to remove. So, you will need to remember the constraints you set up for the button (probably in an instance variable) and remove those. If the initial constraints were set up in IB, then you'll need to set up an outlet to track them.

Resetting a fixed width and height in AutoLayout

I'm creating a custom UIView called CTCycleClock with a subview called CTCycleSlider. It reacts to a gesture so it can rotate on one axis (like looking from above upon a roulette table).
To achieve this, the main view CTCycleClock creates two constraints on the CTCycleSlider subview that center it on X and Y.
Example:
Furthermore, the CTCycleSlider subview creates two constraints on itself that set a specific width and height. This is necessary because otherwise upon rotation, the disk will make itself larger.
This works nicely and correctly. But when the superview has a bigger size (for instance on iPad), I don't know how to tell AutoLayout that the subview has a new fixed width and height equal to the superview.
This is how I set constraints in the superview:
NSLayoutConstraint *centerX = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.f constant:0.f];
NSLayoutConstraint *centerY = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.f constant:0.f];
[self addConstraint:centerX];
[self addConstraint:centerY];
This is how I set constraints in the subview, where self.widthAndHeight is currently hardcoded to 320 on iPhone and 450 on iPad:
NSLayoutConstraint *w = [NSLayoutConstraint
constraintWithItem:self
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:self.widthAndHeight];
NSLayoutConstraint *h = [NSLayoutConstraint
constraintWithItem:self
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:self.widthAndHeight];
[self addConstraint:w];
[self addConstraint:h];
So my question is: how can I make a subview first hug the superview frame with a certain margin, but also set its width and height fixed?
EDIT: some clarifications as to why I need the constraint that sets width/height fixed.
When I won't set the width/height fixed, and the user touch-rotates the wheel, you get the following result:
In the above image, I've set constraints on the subview that set top/lead/width/height to the superview. That works great when the user hasn't rotated the wheel subview yet, but when they do, the autolayout constraints force the rectangular UIView smaller so it completely fits in the superview.
Thus the question remains: how can I create constraints that initially resize the subview correctly to the superview, but then set a fixed width/height so upon rotation, it stays the same size?
...how can I make a subview first hug the superview frame with a
certain margin, but also set its width and height fixed?
I don't understand your question. If you make your image view hug the superview with a fixed margin (on all sides) then the size of the image view is dictated by the superview.
You could pin the image view on 2 sides (e.g. top and left) and specify a size. Then the distance to the other 2 sides would vary based on the size of the superview. Or you could center it in the superview and fix the size, and then ALL The margins would vary based on the size of the superview.

Auto Layout - programatically defining unusual constraints

I'm trying to find examples for some relatively nonstandard layouts, but all the documentation I found only gave examples of centring or aligning with the superview borders, or giving fixed numbers as spaces and sizes.
Can you please advise about programatically defining the following constraints:
A. Diagonal views:
B. Put a view on the third of it's superview's border (or some other ratio which is not the middle)
C. Two standard spaces from the superview's border (like this |-[v1], but with double space)
Any documentation that discusses similar cases would be also highly appreciated :)
Thanks in advance!
You can use the verbose NSLayoutContraint method to create any constraint, that can't be expressed with the visual format language.
A: You need two constraint that describe exactly what you want. In this case you want the top edge of v1 and the bottom edge of v2 be the same. Similarly for the right and left edges.
NSLayoutConstraint *constraint;
constraint = [NSLayoutConstraint constraintWithItem:v1
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:v2
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:v1
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:v2
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0.0];
[self.view addConstraint:constraint];
B: This time you want to top edge of v1 and v2 to be the same:
NSLayoutConstraint *constraint;
constraint = [NSLayoutConstraint constraintWithItem:v2
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:v1
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0];
[self.view addConstraint:constraint];
What constraint to use for the horizontal position of the orange view, depends on what you want. Do you want a fixed margin to the right edge of the blue view?
constraint = [NSLayoutConstraint constraintWithItem:v2
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:v1
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:rightMargin];
[self.view addConstraint:constraint];
C: I don't think you can specify a double space like that. You could either use an ugly trick, and insert an invisible (width 0) view between the standard spaces like this:
|-[invisibleView(0)-[v1]
Or you could just figure out what the standard margin is, and use twice that value as a constant:
|-(doubleMargin)-[v1]

Resources