水平Stackview左对齐项目

时间:2018-08-24 22:24:19

标签: swift uistackview

我正在创建一个水平的UIStackView,并希望将其中的项目左对齐。 这是我的代码:

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
}()

这是我将其添加到视图中的方式

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

我还尝试了以下方法:

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

PS:这个问题与UIStackview align left不同,因为我所说的是水平堆栈视图

根据此链接Left aligned horizontal stackview and top aligned vertical stackview 有没有其他选择,我真的不想设置固定的宽度。

1 个答案:

答案 0 :(得分:0)

在UIViews中包装标签,然后将标签固定在这些视图的左侧。将视图放入堆栈视图中,它们将填充堆栈视图,而无需操作标签。