gpt4 book ai didi

swift - UIStackView - 为什么堆栈一个放在另一个之上?

转载 作者:行者123 更新时间:2023-11-30 10:39:26 27 4
gpt4 key购买 nike

我正在尝试在堆栈 View 中排列一组按钮。但是,当我使用 for-each 循环来执行此操作时,按钮最终会被一个放在另一个的顶部?

 var stackView: UIStackView = {
let sView = UIStackView()
sView.axis = .vertical
sView.distribution = .fill
sView.alignment = .center
return sView
}()

var optionTitles = ["Sign in", "sign out"]

for title in optionTitles{
let btn = UIButton()
btn.setTitle(title, for: .normal)
btn.backgroundColor = optionColour.withAlphaComponent(0.6)
allButtons.append(btn)
stackView.addSubview(btn)
}

// Auto layout constraints
for button in allButtons{
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: optionHeight).isActive = true
button.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true
}

view.addSubview(stackView)
stackTopConstraint = stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
stackBottomConstraint = stackView.bottomAnchor.constraint(equalTo: view.topAnchor)

stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackTopConstraint!.isActive = true
stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

enter image description here

最佳答案

2件事

1-您需要删除此

button.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true

2-替换

stackView.addSubview(btn) 

stackView.addArrangedSubview(btn) 

关于swift - UIStackView - 为什么堆栈一个放在另一个之上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57191992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com