【发布时间】:2018-01-17 10:43:33
【问题描述】:
我见过几个这样的问题,但没有一个答案能帮我解决这个问题。
我在屏幕底部有一个视图,其中包含一个滚动视图,其中包含一个堆栈视图,该堆栈视图将填充按钮。
我的视图是这样以编程方式构建的:
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 环绕按钮而不是填充滚动视图。
任何帮助都会很棒。我确定这是一个简单的修复,我只是看不到它!
【问题讨论】:
-
设置属性填充均等
-
这给出了相同的结果,谢谢
-
设置stackview宽度等于scrollview宽度
-
如果使用约束,我不应该这样做
-
我说需要等宽约束,如果你用 scrollView 嵌套它