Horizontal Stackview left align items

Viewed 2473

I am creating a horizontal UIStackView and want to left align items in it. Here is my code:

let nameLabel: UILabel = {
    let label=UILabel()
    label.text = "First Name:"
    label.textColor = UIColor.black
    label.font = UIFont.systemFont(ofSize: 20)
    label.textAlignment = .left
    label.translatesAutoresizingMaskIntoConstraints=false
    return label
}()

let nameTextField: UITextField = {
    let label=UITextField()
    label.placeholder = "Enter Name"
    label.textColor = UIColor.darkGray
    label.font = UIFont.systemFont(ofSize: 18)
    label.textAlignment = .left
    label.isUserInteractionEnabled = false
    label.translatesAutoresizingMaskIntoConstraints=false
    return label
}()

lazy var firstNameView: UIStackView = {
    let stackView = UIStackView(arrangedSubviews: [self.nameLabel, self.nameTextField])
    stackView.translatesAutoresizingMaskIntoConstraints = false;
    stackView.axis = .horizontal
    stackView.distribution = .fill
    stackView.alignment = .center
    stackView.spacing = 10.0
    return stackView
}()

And here is how i add it to the view

self.view.addSubview(firstNameView)

firstNameView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true;
    firstNameView.topAnchor.constraint(equalTo: idLabel.bottomAnchor).isActive = true;
    firstNameView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    firstNameView.heightAnchor.constraint(equalToConstant: 40.0).isActive = true

I also tried the following:

firstNameView.trailingAnchor.constraint(greaterThanOrEqualTo: self.view.trailingAnchor).isActive = true

PS: This question is different from UIStackview align left as i am talking about horizontal stackview

According to this link Left aligned horizontal stackview and top aligned vertical stackview Is there any alternative, i don't really want to set a fixed width.

1 Answers

Wrap your labels in UIViews and pin the labels to the left of these views. Put the views into the stack view and they will fill the stack view without manipulating the labels.

Related