2

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.

Shivam Pokhriyal
  • 1,044
  • 11
  • 26

1 Answers1

1

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.

Myk
  • 979
  • 6
  • 16
  • I will try this but not really sure if wrapping every label and textfields inside UIView is a good idea. – Shivam Pokhriyal Aug 25 '18 at 07:31
  • Well, let me know how it goes. If I had your issue I would solve it this way so if this method is not correct please let me know =) – Myk Aug 27 '18 at 18:15