我正在开发一个测验应用程序,我想显示一个带有相应选项的问题,但只有一个正确的答案。每个问题对应的数量因问题而异(有些问题有2,3,4等)。通过UIButton显示选择,并将每个按钮添加到UIStackView。按钮的数量取决于问题有多少种可能的选择。例如,如果问题有2个选择,则将2个按钮分配给堆栈视图。
但是,当我在堆栈视图中添加一个按钮时,每个按钮都直接放在彼此的顶部,但是我希望它们在垂直方向上均匀地间隔开。这是我当前的代码:
func viewConfiguration() {
questionView.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true
questionView.widthAnchor.constraint(equalTo: headerView.widthAnchor).isActive = true
questionView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.385).isActive = true
choicesView.topAnchor.constraint(equalTo: questionView.bottomAnchor).isActive = true
choicesView.widthAnchor.constraint(equalTo: questionView.widthAnchor).isActive = true
choicesView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
// Adds question title label to questionVIew hierarchy
let questionLabel = UILabel()
questionLabel.translatesAutoresizingMaskIntoConstraints = false
questionView.addSubview(questionLabel)
questionLabel.backgroundColor = UIColor.yellow
questionLabel.centerXAnchor.constraint(equalTo: questionView.centerXAnchor).isActive = true
questionLabel.centerYAnchor.constraint(equalTo: questionView.centerYAnchor).isActive = true
// Adds question choices to choicesView hierarchy
var questionChoices = [UIButton]()
var buttonStack: UIStackView = {
var stack = UIStackView()
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.distribution = .fillEqually
return stack
}()
let questionData = QuestionData()
questionData.presentQuestion(label: questionLabel, buttons: &questionChoices)
print("NUMBER OF BUTTONS IS --> \(questionChoices.count)")
choicesView.addSubview(buttonStack)
for button in questionChoices {
buttonStack.addArrangedSubview(button)
}
buttonStack.heightAnchor.constraint(equalTo: choicesView.heightAnchor, multiplier: 0.875).isActive = true
buttonStack.widthAnchor.constraint(equalTo: choicesView.widthAnchor, multiplier: 0.9).isActive = true
buttonStack.topAnchor.constraint(equalTo: choicesView.topAnchor, constant: 15).isActive = true
buttonStack.centerXAnchor.constraint(equalTo: choicesView.centerXAnchor).isActive = true
}
蓝色部分是包含按钮的堆栈视图的视图。所显示问题的可能选择是“此处”,“任何地方”,“任何地方”,“那里”,但仅显示最后一个选择。我该怎么做,这样所有选择都可以在stackview中查看,而又不会彼此堆叠?
当前功能的屏幕截图:enter image description here