Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIStackView dynamcially add 2 labels next to each other with no extra spacing

Im new to iOS development and Im a bit confused as to how to achieve this.

I have 2 UILabels added to a UIStackView like so:

let horizontalStackView1 = UIStackView(arrangedSubviews: [self.label1, self.label2])

and when I run the app it looks like this:

enter image description here

However, Id like the labels to be next to each other with no spacing in between something like this: enter image description here

Ive tried setting horizontalStackView1.distribution, horizontalStackView1.alignment etc with no luck.

How do I achieve this?

Thanks in advance!

UPDATE:

The code looks like this (its a cell of a table by the way):

class ItemTableViewCell: UITableViewCell
{
    ...
    let stateLabel = UILabel()
    let effectiveDateLabel = UILabel()
    ...

    var typeImage: UIImage?
    {
        ...
    }

    var summary: String?
    {
        ...
    }

    var effectiveDate: Date?
    {
        ...
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.accessoryType = .disclosureIndicator
        ...
        let horizontalStackView1 = UIStackView(arrangedSubviews: [self.stateLabel, self.effectiveDateLabel])
        let horizontalStackView2 = UIStackView(arrangedSubviews: [typeImageViewWrapper, self.titleLabel])
        horizontalStackView2.spacing = 4
        let verticalStackView = UIStackView(arrangedSubviews: [horizontalStackView1, horizontalStackView2, self.summaryLabel])
        verticalStackView.axis = .vertical
        verticalStackView.spacing = 4
        self.contentView.addSubview(verticalStackView)
        ...
    }

    required init?(coder aDecoder: NSCoder)
    {
        fatalError()
    }
}
like image 864
David Kroukamp Avatar asked Dec 01 '25 22:12

David Kroukamp


1 Answers

That's because the UIStackView picks the first arrangedSubview with lowest content hugging priority and resizes it so the stackview's content takes up full width.

If you want to use UIStackView for this case, you can should change the content hugging priorities, eg.

label2.setContentHuggingPriority(.defaultLow, for: .horizontal)
label1.setContentHuggingPriority(.defaultHigh, for: .horizontal)
like image 120
Michal Klein Avatar answered Dec 04 '25 14:12

Michal Klein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!