我见过几个像这样的问题,但没有一个答案能够解决这个问题。
我在屏幕底部有一个视图,其中包含一个scrollView,其中包含一个将用按钮填充的stackView。
我的视图是以编程方式构建的:
import UIKit
class BottomBar: UIView {
typealias BindTap = ((String) -> Void)?
private let scrollView = UIScrollView()
private let buttonsStackView = UIStackView()
var onTap: BindTap
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpViews()
setUpLayout()
}
private func setUpViews() {
backgroundColor = .cyan
scrollView.backgroundColor = .red
buttonsStackView.backgroundColor = .green
buttonsStackView.alignment = .fill
buttonsStackView.distribution = .equalSpacing
buttonsStackView.axis = .horizontal
buttonsStackView.spacing = 5
scrollView.addSubview(buttonsStackView)
addSubview(scrollView)
}
private func setUpLayout() {
buttonsStackView.pinToSuperview(edges: [.top, .bottom, .left, .right],
constant: 5,
priority: .defaultHigh)
scrollView.pinToSuperview(edges: [.top, .bottom, .left, .right],
constant: 0,
priority: .defaultHigh)
}
func addModelButtons(models: [Model]) {
models.forEach { model in
let modelButton = UIButton()
modelButton.backgroundColor = .lightGray
modelButton.setTitle(model.fileName, for: .normal)
modelButton.addTarget(self, action: #selector(modelButtonTapped), for: .touchUpInside)
buttonsStackView.addArrangedSubview(modelButton)
if let first = models.first,
first.fileName == model.fileName {
updateSelectedButtonColor(modelButton)
}
}
}
@objc private func modelButtonTapped(button: UIButton) {
guard let modelName = button.titleLabel?.text else { return }
onTap?(modelName)
resetButtonColors()
updateSelectedButtonColor(button)
}
private func resetButtonColors() {
for case let button as UIButton in buttonsStackView.subviews {
button.backgroundColor = .lightGray
}
}
private func updateSelectedButtonColor(_ button: UIButton) {
button.backgroundColor = .darkGray
}
}
我无法看到遗漏的东西。我已添加了一张图片,因此您可以看到stackView正在环绕按钮而不是填充滚动视图。
任何帮助都会很棒。我确定它是一个简单的修复我只是看不到它!
答案 0 :(得分:3)
这是关于scrollViews的理解。除非您为scrollView的内容区域指定显式大小,否则它将根据其子视图确定其大小。
在你的情况下,你已经告诉它你的stackView距离scrollView的边缘5
点。这将stackView的大小与scrollView的内容区域的大小联系起来。此时,stackView控制scrollView的可滚动区域的大小。由于您的stackView只有2个按钮,因此stackView缩小到这两个按钮的大小,并且scrollView的可滚动区域比10
更宽。由于按钮很小,这不会填满屏幕。
你想要的是按钮伸展以填充scrollView的表观大小。为了实现这一点,您需要告诉自动布局,stackView的宽度必须大于或等于 scrollView的宽度 - 10
。
在scrollView.addSubview(buttonsStackView)
之后添加此约束:
buttonsStackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor, multiplier: 1, constant: -10).isActive = true