UIStackView,自定义大小的元素和项目在中心- Swift -编程

7d7tgy0s  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(164)

我想设置一个UIStackView与3个视图的底部,使中心视图定位在中心和其他意见进行相应的调整,我也希望能够设置所有3个意见的宽度和高度锚。这是预期的结果:

这就是我得到的

这是我正在使用的代码:

bottomStackView = UIStackView(arrangedSubviews: [pickerView, downloadContentButton,  shareButton])
    bottomStackView.alignment = .center
    bottomStackView.distribution = .fill
    bottomStackView.axis = .horizontal
    bottomStackView.spacing = 5
    bottomStackView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bottomStackView)
    
    bottomStackView.anchor(top: nil, leading: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.trailingAnchor)
    bottomStackView.heightAnchor.constraint(equalToConstant: 150).isActive = true
    bottomStackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    
    pickerView.heightAnchor.constraint(equalToConstant: 120).isActive = true
    shareButton.heightAnchor.constraint(equalToConstant: 150).isActive = true
    shareButton.widthAnchor.constraint(equalTo: pickerView.widthAnchor).isActive = true
    
    downloadContentButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
    downloadContentButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
    
    shareButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
    shareButton.heightAnchor.constraint(equalToConstant: 80).isActive = true
n9vozmp4

n9vozmp41#

我觉得你在追求这样的东西:

或者,如果我们得到更广泛的:

如果这就是你的想法,那么一个关键的错误就是当你说:

bottomStackView.distribution = .fill

你真的想要.equalDistribution。为了演示,我完全用代码创建了这个示例,所以你可以看到所有的设置:

let sv = UIStackView()
sv.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(sv)
sv.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
sv.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
sv.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20).isActive = true
sv.heightAnchor.constraint(equalToConstant: 160).isActive = true

sv.distribution = .equalSpacing
sv.alignment = .center

let v1 = UIView()
v1.translatesAutoresizingMaskIntoConstraints = false
v1.widthAnchor.constraint(equalToConstant: 120).isActive = true
v1.heightAnchor.constraint(equalToConstant: 150).isActive = true
v1.backgroundColor = .red
sv.addArrangedSubview(v1)

let v2 = UIView()
v2.translatesAutoresizingMaskIntoConstraints = false
v2.widthAnchor.constraint(equalToConstant: 80).isActive = true
v2.heightAnchor.constraint(equalToConstant: 80).isActive = true
v2.backgroundColor = .yellow
sv.addArrangedSubview(v2)

let v3 = UIView()
v3.translatesAutoresizingMaskIntoConstraints = false
v3.widthAnchor.constraint(equalToConstant: 120).isActive = true
v3.heightAnchor.constraint(equalToConstant: 150).isActive = true
v3.backgroundColor = .blue
sv.addArrangedSubview(v3)

相关问题