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.
Related
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.
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 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
I have a View controller, in which the view has two image views and two text views. I turned off auto layout, and I programmatically set the distance between the first text view and the first image view by using this code:
The following code is in the viewDidLoad method of my custom view controller class. I have set the autoresizing mask to no in both cases, so I have no idea why the code doesn't work.
(tf2_logo is the image view and itemName is the text view)
self.tf2_logo.translatesAutoresizingMaskIntoConstraints = NO;
[self.backpackBackground addConstraint:[NSLayoutConstraint constraintWithItem:self.itemName attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.tf2_logo attribute:NSLayoutAttributeTop multiplier:1.0 constant:-1.0]];
[self.backpackBackground addConstraint:[NSLayoutConstraint constraintWithItem:self.tf2_logo attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.backpackBackground attribute:NSLayoutAttributeLeft multiplier:1.0 constant:17]];
Now I want to do the same thing with my other text view, basically I wanted to keep the distance between the itemName text view and the text view at a certain distance. I used this code:
(tf2 is my other text view)
self.tf2.translatesAutoresizingMaskIntoConstraints = NO;
[self.backpackBackground addConstraint:[NSLayoutConstraint constraintWithItem:self.itemName attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.tf2 attribute:NSLayoutAttributeTop multiplier:1.0 constant:-3.0]];
[self.backpackBackground addConstraint:[NSLayoutConstraint constraintWithItem:self.tf2 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.tf2_logo attribute:NSLayoutAttributeRight multiplier:1.0 constant:20]];
After implementing this code, the tf2 text view doesn't even show up in the view controller. What is the problem?
EDIT: You can download the whole project here: https://www.dropbox.com/sh/u820u2ndyrncuz8/P4atI-9CAx
EDIT#2:
You mentioned that you turned off auto layout, because UITextView has that little gap on top in iOS7. To remove the gap, try this:
self.tf1.textContainerInset = UIEdgeInsetsZero;
When you log the original value of the textContainerInset it shows: {8, 0, 8, 0} . The two 8's are responsible for the gap (one at the top). The line above sets all values to zero and the content is nicely aligned to the top of the frame.
(EDIT#1: Completely changed the answer)
I assume you primarily want to have a flexible height of the imageName UITextView. First I suggest to use auto layout. You can set constraints in Xcode according to the following image:
The red lines are the constraints. The green line is special: It shall be a height constraint and you create an outlet for it in the view controller. (Open the document outline view, locate the height constraint in the tree and control-drag it to the code.)
Then in the viewDidLoad method:
CGSize size = [self.tf1 sizeThatFits:self.tf1.frame.size];
self.tf1Height.constant = size.height;
The height of the "lore ipsum" field now adjusts to its content.
Have you tried using frames instead of constraints? If your not using autolayout I think frames might be easier to read/implement.
sample:
// tf2 will be placed at (0,0) in superview and have width of 100 and height of 20
tf2.frame = CGRectMake(0, 0, 100, 20);
you can play around with different values to get your layout as desired.
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.