Swift UIStackView:以编程方式从中心定位元素

问题描述 投票:5回答:1

我正在尝试使UIStackView内的元素从中心位置相等。

这是我想要的效果:

enter image description here

如您所见,我希望两个文本字段彼此等距并在堆栈视图中居中对齐。

此堆栈视图将包含我需要排队的1-7个文本字段。

以下是当前发布的内容:

enter image description here

这是我设置文本字段的方式

let textLabel = UILabel()
textLabel.backgroundColor = UIColor.red
textLabel.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi"
textLabel.textAlignment = .center

let textLabel1 = UILabel()
textLabel1.backgroundColor = UIColor.red
textLabel1.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
textLabel1.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel1.text  = "Hi"
textLabel1.textAlignment = .center

我正在像这样生成堆栈视图:

//Stack View
let stackView   = UIStackView()
stackView.axis  = UILayoutConstraintAxis.horizontal
stackView.distribution  = UIStackViewDistribution.equalCentering
stackView.alignment = UIStackViewAlignment.fill
stackView.spacing   = 16.0

stackView.addArrangedSubview(textLabel)
stackView.addArrangedSubview(textLabel1)
stackView.translatesAutoresizingMaskIntoConstraints = false;

self.view.addSubview(stackView)

//Constraints

stackView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 50).isActive = true
stackView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -50).isActive = true
stackView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true

如何获得内部的元素以使其居中对齐?

我以为是

UIStackViewDistribution.equalCentering

但是,那没什么大作用。

swift uistackview
1个回答
7
投票

太奇怪了。通常,具有中心对齐和相等的中心分布的水平UIStackView应该完全做到这一点:

enter image description here

enter image description here

enter image description here

但是也许我不理解您的正确,而您实际上想要这样的东西:

enter image description here

在这种情况下,您必须选择“均等填充”作为分配方法,并使标签本身位于文本的中心:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.