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.