我试图将一组按钮排列在堆栈视图中。但是,当我使用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
答案 0 :(得分:0)
两件事
1-您需要删除此
button.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true
2-替换
stackView.addSubview(btn)
使用
stackView.addArrangedSubview(btn)
答案 1 :(得分:0)
您有:
stackTopConstraint = stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
stackBottomConstraint = stackView.bottomAnchor.constraint(equalTo: view.topAnchor)
您可能在第二行中表示view.bottomAnchor
。当然,您不想将堆栈视图的底部限制为视图的 top 。