Align two labels in a table cell? - ios

I am having pretty crazy amounts of issues trying to align two labels inside a table cell:
The problem is I need both labels (the region is clickable) to be centred within their cell. I can only seem to get the layout centred based one or the other.
Is this too much to expect from autolayout?

Embed the labels in a new view, then centre that view with autolayout. Also, let this new view resize itself according to the labels
So:
- Add leading and trailing constraints between labels and their superview (new view)
- Centre the new view in the UITableViewCell
I just got home, so I opened up a fresh project, with good news :)
So I set up what I described earlier, 2 labels inside an UIView
Select the labels and go to the Size Inspector, there check 'Explicit' and in the 'Preferred Width' add the Maximum - make it the maximum it is allowed to be
Now in code, you can set the labels and they auto-resize!

Related

Design UIView so that it can dynamically change its height based on the content height

In a XIB file I have a CustomView related to a class with the same name.
The view content is quite simple.
There are a vertical stackview and inside the stackview there are two labels. The stackview is vertically aligned to the view that contains it:
The first label (title) contains a static text (always a few characters).
The second label (subtitle) can have variable length text.
I add this CustomView with other similar views as a subview of a Content View, as it was a “row”.
for i in 0...aViews.count {
var v = CustomView(frame: CGRect(x: 0, y: _y, width: 320, height: 100))
v.labelText = "my long label text ..."
contentView.addSubview(v)
// ...
}
As you can imagine, the title label should have a fixed position (top and left), that is, there cannot be a row with the title starting at 10 points and another at 14.
I must admit I naively thought the position of the label would have been automatically managed by the same fact that I aligned vertically the stackview. I was wrong and I noticed no problem at all, until they told me the second label, the subtitle, could contain more than one line.
I added lines to the label directly in the storyboard, and found out that:
the container of the stackview doesn’t change its height based on the height of its content;
the position of the “fixed” elements is maybe vertically centered but not fixed;
What I need is the following:
the labels should be “grouped” and aligned vertically: there should be the same amount of space from the top of the first label to the upper border of the container and from the bottom of the second label to the bottom border;
when the second label has to display more than one line, the container view should change its height accordingly;
Is this possible? How should I design my view?
OK - looking at your project, you're not far off... just a couple key items.
In your CustomView.xib, you had no constraint between Fixed Label and Date Label. The result is that the Date Label grows up from the bottom of the view, with nothing to stop it.
Also in your CustomView.xib, you had the Fixed Label constrained to the trailing edge... I assume you want it left-aligned with Date Label
When creating your CustomViews, you were setting a height constraint of 100 -- which defeats the purpose of allowing the content to determine the size.
In CustomView class, you had contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] commented out. That line should be there.
In your view controller, you added a height constraint to contentView with a low priority. Best option is to make that a Placeholder constraint (double-click the constraint, and select the Placeholder checkbox). That way the constraint is removed at run-time, but is there during design (and Storyboard doesn't complain).
You were doing a few other un-necessary things - likely you were trying different stuff to get it to work.
The view setup (adding your views) is best done in viewDidLoad() -- definitely not in viewDidLayoutSubviews()
I'm guessing that, in your CustomView, instead of an explicit width of 200 you probably want to constrain the Date Label leading and trailing, allowing it to horizontally stretch based on the device width... but I left it at 200.
If you can follow that information, you should be able to fix the issue(s). But, I put the project up as a GitHub repo for you, so you can get it in a "working" state, and so you can see the changes.
Here's the link to the repo: https://github.com/DonMag/ATester2
Here is the result:
And scrolled up a bit:
I think you are mixing absolute positioning of outer views (i.e. manually setting frames) and using autolayout constraints for their inner components, and wrongly expect the dynamic autolayout part to somehow "reach all the way up" to the outer views. For autolayout to do that, you'll need to use autolayout all the way up, including the way CustomViews are positioned in your contentView.
If for whatever reason you do not want to use a TableView or CollectionView for this you could also, for example, try adding your CustomViews as arranged subviews to a vertical stackview that has top/bottom/leading/trailing constraints to contentView, then replace the "Align Center Y" constraint of your CustomView with "Align Top" and "Align Bottom" constraints to actually allow your labels to "push" from the inside if they need more vertical space.
Edit here's a quick sketch to illustrate that setup:
Edit 2 here are a couple of screenshots to clarify further. With a basic layout like this:
the result will look like this at runtime:
Note that the UIStackViews use the "Equal Spacing" Distribution in this example. If you want to create and add your CustomViews programmatically, use the StackView's func addArrangedSubview(_ view: UIView).
Good luck!

Horizontal UILabels inside a self sizing UITableViewCell

Question: How can I use constraints in a UITableViewCell using UITableViewAutomaticDimension when there are labels side by side which can each contain a different number of lines?
I have a table with cells that contain labels side by side:
I'm having a hard time getting the cell to size properly if one of the labels on one side have more lines than the corresponding label on the other side. One of the labels always gets cut off. If both labels have the same number of lines, the cell resizes perfectly and all text can be seen.
I've tried a number of constraint tweaks but nothing is working perfectly as desired.
I've tried adding hidden label for height...but it doesn't work well for the cell with 4 labels
I've tried placing the labels in a view but then the height of the view still needs to be calculated.
Currently the constraints are setup normally: top, bottom, left , right, labels are set to 0 lines etc and works great when both labels have the same text or same number of lines.
Is there any way I can do this with constraints? Or do I need to revert to the old height for row at index path? =(
There is a way to achieve what you want to do just using constraints. The trick is to set the relation of the constraints between the two lower labels and the bottom to Greater Than or Equal instead of equal.
Here is how I set the constraints:
Which has this result:
Or you could set the constraints between the labels top and bottom to Greater Than or Equal and leave the bottom constraint at equal:
To get this result:
I found a solution where I did not have to revert to using tableView:heightForRowAtIndexPath.
I added a label to the cell with the text color set to clearColor and called it 'heightLabel'. I added constraints to the heightLabel so the cell would resize based on the heightLabel's constraints.
Then whichever of the left or right labels had the most text, I placed that label's text inside the heightLabel.
The cells still were not resizing and I had to call 'layoutIfNeeded' on the cell before returning the cell in tableView:cellForRowAtIndexPath.
The heightLabel constraints are now what is being used to resize the cell and UITableViewAutomaticDimensions is working properly.
This may not be the best solution but it's working out pretty well. If there is a more proper way of doing this I'm open to suggestions.

Center multiple UILabels on a line

I want to horizontally center multiple UILabels - as a group - on a line in Interface Builder. One the straight view controller i could not figure out how to do this. I read comments about place the UILabels in a View and then centering the view in the view controller. When I tried this, overtime I said to update frames in the interface builder, the View would be resized down to nothing. (i.e. its height and width would be set to 0 by IB). I need to know how to get this to work in interface builder.
An example of a line containing multiple labels I want horizontally centered is below. The braces simply indicate the start and end of each label and are not art of the text. The <- 6 -> is meant to indicate the trailing space from label 1 to label 2 is 6
Label 1 Label 2
[Rating: 0.0]<- 6 ->[Distance: 125.34 Kilometers]
Any suggestions would be greatly appreciated.
Here is an EXACT example of what I have done and it does not work:
Create a new view controller in IB
Place a page label at the top of the page centered horizontally and aligned to the top of the layout guide.
Add a view with the following constraints on the page:
Now add two labels to the view with the following constraints:
Once this is done I get the following error and updating the frames will cause it to be give a height and width of 0
Here is what the page looks like in IB:
I need the height and width of the view to size automatically so that I have put a multiline label in the view and have all the contents of the view treated as a group and centered on the page.
Any suggestions would be greatly appreciated.
Here is a snapshot of a working set of all the constraints on an abbreviated layout that produces an always-centered view that automatically resizes with the child views (i.e., as the content of any label changes, the view grows or shrinks around it).
Important to your solution, the view has neither a height nor width constraint; its size is constrained entirely by its descendant constraints.
The key is that every component has a direct or indirect constraint from which its size and position are specified or can be inferred. For example, in order for the view to infer its width, the child labels must have a leading space constraint on the first label, a trailing space constraint on the last label, and a horizontal space constraint between interior labels. Those constraints plus the contents of the labels allow the width of the view to be inferred ... and force the view to dynamically conform to that width.
The same applies for the view's height. For example, you can specify the top and bottom space of just one label, or all of them. If just one, the remaining labels can be vertically aligned with it (see "Align Center Y to: Label1" in the screenshot).

same space retain between three label using autolayot

I am learning auto layout from last two days, i have one UITableViewCell xib file and in this cell there is two Labels and one Button, How can i manage Horizontally and vertically space between this subviews of cell?
Thanks in advance.
This trick is to add empty placeholder UIViews between your labels/buttons and bind them with an Equal Width constraint.
Following images show how it is done for horizontal spacing. Purple colored views are the placeholder UIViews. You can later set their alpha=0 or make them hidden so they will not appear when the app is running.

How to center horizontally two labels?

I have pretty straightforward requirements where two labels must be centered horizontally. So, I have selected them and chose Editor->align->center horizontally. Then added top space to container constraint to both of them. I also need the labels to shrink/grow regarding content size. However, IB shows errors and several warnings. I could make the labels shrink/grow just by adding pin between them (horizontal space) but they will not be centered in that case. Here are the screenshots:
here are the errors and warnings:
UPDATE theraven gave an interesting suggestion to use dummy view for centering it horizontally and pinning two labels to it. I have removed all existing constraints, added this dummy view and center X + center Y constraints to it. Then pined two labels to it (added horizontal space constraints). However, I still get a bunch of errors and warnings:
UPDATE2 Just updating the question, but still no valid answer found. #Theraven workaround works for iPhone4, iPhone4S, iPhone5 and iPhone5S, however it's not real centering but rather a workaround. Therefore for iPhone6 and iPhone6 Plus it doesn't work as leading and trailing spaces will be fixed and won't automatically resize for larger width.
What you could do is add both labels to another view, like a container view. Then you need to center this one horizontally and add the necessary constraints.
To add the containing UIView, you can select both labels, go to Editor -> Embed In -> View.
Then you would need to add constraints to make the containing view fit the two labels. So something like this:
First Label (left one):
Leading Space to Superview
Top and bottom Space to Superview
Horizontal spacing to the next Label
Second Label:
Trailing space to superview
Top and Bottom to superview (or align top with the first one)
Then the containing view should resize as to fit both labels. Then all you need to do is add the top offset constraint for this container view and a horizontal alignment it in the parent view.
This way, the containing view will grow as much as it needs to fit both labels and the space between them and will always be centered in the parent view.
I took a screenshot of my test constraints in case it helps you more.
Hope this was what you were looking for.
To solve this use a blank UIView in between your two labels and center it horizontally. Then pin the two labels either side of the centered blank view. It is common convention to use spacer views like this in auto-layout.
I really don't like the idea of adding another view just for sake of estethic.
Another alternative is to horizontally-center the left view, and horizzontally space the right view of an amout X with the left one.
Then to give the horizontally-align contraint of the first view a negative value equal to the first view width plus half the views distance. Or use multipliers as said in a previous comment.
But this only works with fixed width views i guess.
Use centered UIStackView as a container for two labels with a spacing required.
I didn't really understand what you wish to do.
The error you get (in the first screen shot) is that you are missing constraint for the x position of the labels.
For UILabel you must have constraint both for y and for x position regarding to the container view, when you selected them both and chose Editor->align->center horizontally, you just say that label1.center.x = label2.center.x.
You still need to say where they will be in the container view, you added the top space to container, so you do have the y position, but you didn't say where the x position should be.
You said
I have pretty straightforward requirements where two labels must be centered horizontally
But where they should be in respect to their container?
thanks
Using spacer views is the best possible solution I could figure out, even though it looks ugly for the developer. The user wouldn't even know what's going on behind the scenes and once you have the spacer UIView, you can always reuse it.

Resources