Search code examples
iosswiftuitableviewuistackview

Layout for 2 UILabels on UITableViewCell


I wish to have 2 labels on custom table view cell. First label should be on left 15 points away from left margin and 2nd label should be on right 15 points away from right margin. It can grow internally. Since the label is not going to display lots of data, it surely won't overlap on each other.

I am using stack view. Below are the images for my custom xib file. Number of lines for both the label is set to 1. When I launch, I see a blank cell without the labels. What is missing?

enter image description here

enter image description here

enter image description here

enter image description here

EDIT: Adding more details. I updated distribution on UIStackView to Fill Equally and updated alignment for 2nd label i.e start time label to right. I am seeing the data on the cell now, but 2nd label is not getting aligned to right.

enter image description here

enter image description here Code in cellForRow:

let cell = tableView.dequeueReusableCell(withIdentifier: "displayStartTime") as! ScheduleDisplayStartTimeCustomCell
cell.selectionStyle = UITableViewCell.SelectionStyle.gray
cell.titleLabel.text = "Start"
cell.timeLabel.text = startTime
return cell

This is how it looks now after the edit:

enter image description here


Solution

  • Storyboard solution:

    You can select the distribution for the StackView to equal spacing in the storyboard, with the default spacing value. The Labels only need the height contraint after that (or you could set the height for the StackView), and will be positioned to the sides of the StackView.

    Resulting cell

    The text alignment in the Label won’t matter, as the Label will be only as wide as needed.