我正在尝试实现以下布局(视图水平居中):
所以我设置了一个堆栈视图,如下所示:
let quickPromptsView: UIStackView = {
let sv = UIStackView()
sv.axis = .horizontal
sv.alignment = .center
sv.distribution = .equalSpacing
sv.spacing = 10
sv.translatesAutoresizingMaskIntoConstraints = false
return sv
}()
向堆栈视图添加按钮:
func addOptions(options: [DialogNodeOutputOptionsElement]) {
DispatchQueue.main.async {
// clear all subviews
self.quickPromptsView.subviews.forEach { (view) in
view.removeFromSuperview()
}
for option in options {
let button = QuickPromptButton()
button.setTitle(option.label, for: .normal)
button.addTarget(self, action: #selector(self.didTapQuickPrompt), for: .touchUpInside)
self.quickPromptsView.addArrangedSubview(button)
}
}
}
按钮类:
class QuickPromptButton: UIButton {
var userFacingValue: String?
var answerValue: String?
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderColor = UIColor.primaryColor.cgColor
layer.borderWidth = 1
layer.cornerRadius = 15
setTitleColor(.primaryColor, for: .normal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这就是我添加堆栈视图的方式,我将它添加到MessageKit的另一个堆栈部分中
func configureQuickPromptsView() {
view.addSubview(quickPromptsView)
quickPromptsView.heightAnchor.constraint(equalToConstant: 40).isActive = true
// this stack view belongs to the MessageKit library
messageInputBar.topStackView.axis = .horizontal
messageInputBar.topStackView.distribution = .fill
messageInputBar.topStackView.addArrangedSubview(quickPromptsView)
}
但是,这就是我得到的:
堆栈视图具有 100% 的屏幕宽度。我已经尝试了每一种类型,distribution
但没有奏效。我还尝试UIView
在极端情况下插入透明 s 以强制居中,但这似乎是一种技巧。有任何想法吗?