[英]Add buttons to UIScrollView Swift 5 programmatically
I'm trying to add a number of buttons programmatically in a grid, where the number of rows exceeds the screen size, so I want them in a UIScrollView.我试图以编程方式在网格中添加许多按钮,其中行数超过屏幕大小,所以我希望它们在 UIScrollView 中。
My minimal working example is the following:我的最小工作示例如下:
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)
}
}
Unfortunately the scrolling doesn't work.不幸的是,滚动不起作用。 Even when I explicitly set a larger vertical content size (see commented line)
//scrollView.contentSize
即使我明确设置了更大的垂直内容大小(请参阅注释行)
//scrollView.contentSize
I'm wondering if it has something to do with setting x and y values for the buttons fixed?我想知道它是否与为固定按钮设置 x 和 y 值有关? But then how else would I align them in a grid?
但是,我还能如何在网格中对齐它们?
So, how do I get the button alignment I want while getting a working ScrollView?那么,如何在获得工作 ScrollView 的同时获得我想要的按钮对齐方式?
I did the same thing with a collection view which is a subclass of scrollview and that would fit your need in terms of rows/columns.我对集合视图做了同样的事情,它是滚动视图的子类,它可以满足您在行/列方面的需求。
In addition, to manage touches for a scrollview you have to implement a UIScrollViewDelegate for the scrollview, in particular to distinguish between touching and scrolling otherwise you will possibly end up with unpredictable behaviour.此外,要管理滚动视图的触摸,您必须为滚动视图实现 UIScrollViewDelegate,特别是要区分触摸和滚动,否则最终可能会出现不可预测的行为。
You really should be using Auto-Layout!!!你真的应该使用自动布局!!!
By far, the easiest way to add buttons (or any view) to a scroll view - in a grid layout like you're asking - and have it automatically determine the scrolling area is with stack views.到目前为止,将按钮(或任何视图)添加到滚动视图的最简单方法 - 在您要求的网格布局中 - 并让它自动确定滚动区域是使用堆栈视图。
Here's a quick example:这是一个快速示例:
class ViewController: UIViewController {
let label = UILabel()
let scrollView = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad()
// start with some text in the label
label.text = "Tap a button"
// center the text in the label
label.textAlignment = .center
// so we can see the frames
label.backgroundColor = .yellow
scrollView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
// create a vertical stack view to hold the rows of buttons
let verticalStackView = UIStackView()
verticalStackView.axis = .vertical
// we're going to use auto-layout
label.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
verticalStackView.translatesAutoresizingMaskIntoConstraints = false
// add label to view
self.view.addSubview(label)
// add Scrollview to view
self.view.addSubview(scrollView)
// add stack view to scrollView
scrollView.addSubview(verticalStackView)
// now let's create the buttons and add them
var idx = 1
for row in 0...20 {
// create a "row" stack view
let rowStack = UIStackView()
// add it to the vertical stack view
verticalStackView.addArrangedSubview(rowStack)
for col in 0...4 {
let button = UIButton()
button.backgroundColor = .gray
button.setTitle("\(idx)", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
// add button to row stack view
rowStack.addArrangedSubview(button)
// buttons should be 50x50
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: 50.0),
button.heightAnchor.constraint(equalToConstant: 50.0),
])
idx += 1
}
}
// finally, let's set our constraints
// respect safe-area
let safeG = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain label
// 50-pts from top
// 80% of the width
// centered horizontally
label.topAnchor.constraint(equalTo: safeG.topAnchor, constant: 50.0),
label.widthAnchor.constraint(equalTo: safeG.widthAnchor, multiplier: 0.8),
label.centerXAnchor.constraint(equalTo: safeG.centerXAnchor),
// constrain scrollView
// 50-pts from bottom of label
// Leading and Trailing to safe-area with 8-pts "padding"
// Bottom to safe-area with 8-pts "padding"
scrollView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 50.0),
scrollView.leadingAnchor.constraint(equalTo: safeG.leadingAnchor, constant: 8.0),
scrollView.trailingAnchor.constraint(equalTo: safeG.trailingAnchor, constant: -8.0),
scrollView.bottomAnchor.constraint(equalTo: safeG.bottomAnchor, constant: -8.0),
// constrain vertical stack view to scrollView Content Layout Guide
// 8-pts all around (so we have a little "padding")
verticalStackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor, constant: 8.0),
verticalStackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: 8.0),
verticalStackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -8.0),
verticalStackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -8.0),
])
}
@objc func buttonAction(sender: UIButton!) {
label.text = sender.title(for: .normal)
}
}
and this is the result:这是结果:
then we'll scroll down and tap a different button:然后我们将向下滚动并点击另一个按钮:
If you want spacing between the buttons, you can add something like this at the end of viewDidLoad()
:如果你想要按钮之间的间距,你可以在
viewDidLoad()
的末尾添加这样的东西:
// suppose we want 8-pts spacing between the buttons?
verticalStackView.spacing = 8.0
verticalStackView.arrangedSubviews.forEach { v in
if let stack = v as? UIStackView {
stack.spacing = 8.0
}
}
Now it looks like this:现在它看起来像这样:
If you want the grid of buttons centered horizontally, or if you want the spacing (or button sizes) to adjust to fit, there are a few different ways to do that... You didn't describe your ultimate goal in your question, but this should be a good starting point.如果您希望按钮网格水平居中,或者如果您希望调整间距(或按钮大小)以适应,有几种不同的方法可以做到这一点......您没有在问题中描述您的最终目标,但这应该是一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.