【发布时间】:2021-10-04 16:04:17
【问题描述】:
我正在尝试以编程方式在网格中添加一些按钮,其中行数超过了屏幕大小,所以我希望它们在 UIScrollView 中。
我的最小工作示例如下:
class ViewController: UIViewController {
//center label and down a bit
let label = UILabel(frame: CGRect(x: UIScreen.main.bounds.width/2 - 100, y: 50, width: 200, height: 200))
// start scroll view underneath label (why not y: 250?)
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 50, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
override func viewDidLoad() {
super.viewDidLoad()
// add label to view
self.view.addSubview(label)
// add Scrollview
self.view.addSubview(scrollView)
// uncommenting the following also doesn't work
//scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: 4000)
// add buttons to scroll view in 5x21 grid
var idx = 1
for row in 0...20 {
for col in 0...4 {
let button = UIButton(frame: CGRect(x: col*50, y: row*50 + 200, width: 50, height: 50))
button.backgroundColor = .gray
button.setTitle("\(idx)", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
// add button to scroll view
scrollView.addSubview(button)
idx += 1
}
}
}
@objc func buttonAction(sender: UIButton!) {
label.text = sender.title(for: .normal)
}
}
不幸的是,滚动不起作用。即使我明确设置了更大的垂直内容大小(参见注释行)//scrollView.contentSize
我想知道它是否与为固定按钮设置 x 和 y 值有关?但是,我还能如何将它们排列在一个网格中呢?
那么,如何在获得正常工作的 ScrollView 时获得所需的按钮对齐方式?
【问题讨论】:
-
“向滚动视图添加按钮”是什么意思?您必须在滚动视图中添加按钮。
-
自从我使用 UIKit 已经有一段时间了,但我相信你想要 1) 在滚动视图中使用堆栈视图并添加排列的子视图或 2) 将子视图约束到滚动视图边界.
-
其实说了这么多,你有没有给滚动视图和它的内容添加任何约束?
-
我正在使用类似的东西,但水平。缩略图图像。毕竟,表/堆栈/集合视图只是滚动视图的“版本”。在它的基础上,您需要定义一些东西 - UIViews、UIScrollView 和(也许这是问题)它的内容大小,当然还有约束。不要忘记这些。我猜?你定义内容大小太早了——
viewDidLoad从来没有为我工作过。在 VC 生命周期中为时过早。试试viewDidAppear,等一切框架都建立好了。 -
@ElTomato 真的吗?但只是通过
scrollView.addSubview(button)添加它似乎工作正常。滚动部分除外。
标签: ios swift uiscrollview uibutton