Custom UITableViewCell - adjust UILabel vertical alignment dynamically
Custom UITableViewCell - adjust UILabel vertical alignment dynamically
I have a custom table cell. It has two labels (title and description), one below the other.
title
description
What I have right now is, title label top = topMargin. And description label top = title label bottom + 10.
title
top = topMargin
description
top = title
bottom + 10
But in some cases, there will be no description. In such cases, I want the title label to be centered vertically inside the cell. Is this possible? What constraints do I have to set?
title
Edited my answer.
– Rakesha Shastri
yesterday
@skt you can used stackview for manage this type of condition
– chirag shah
yesterday
@DonMag the labels will always be single line and the rows are fixed height.
– SKT
4 hours ago
2 Answers
2
A UIStackView makes it easy to do what you want.
UIStackView
0
67
IBOutlet
When you set the text of the labels in cellForRowAt indexPath:, set the description label's .isHidden property to true if it has a description, or to false if it doesn't.
cellForRowAt indexPath:
.isHidden
true
false
The result (with background colors for clarity):

The result without background colors:

Yes this is possible. Center-ing it to the x-axis.
Have a containerView which holds both the title and description.
Center align the containerView.
Fit the title leading to the container leading.
Fit the description leading to the title trailing.
Fit the description trailing to the container trailing.
Add the remaining anchors to suit your needs.
Center-ing it to the y-axis.
Have a containerView which holds both the title and description.
Center align the container.
Fit the title top and leading to the container top and leading.
Fit the description top to title bottom + 10.
Fit the description leading to title leading or whatever is necessary.
Fit the description bottom to containerBottom.
Edit: I did not read the question properly the first time. My bad. This should work. If the description is not present, it'll have width 0 and the title will be centered.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Are your labels single-line only, and the rows are fixed-height? Or are the labels multi-line, so the row heights need to be dynamic?
– DonMag
yesterday