简体   繁体   English

如何在滚动视图中垂直居中堆栈视图的元素?

[英]How to center elements of a stack view in a scroll view vertically?

I have this code I found to put a stack view with many buttons inside of a scroll view.我有这段代码,我发现它可以在滚动视图中放置一个带有许多按钮的堆栈视图。

import UIKit
import SnapKit

class ViewController: UIViewController {
    var scrollView: UIScrollView!
    var stackView: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let scrollView = UIScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(scrollView)
        
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let stackView = UIStackView()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .vertical
        scrollView.addSubview(stackView)
        
        stackView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        for _ in 1 ..< 100 {
            let vw = UIButton(type: UIButtonType.system)
            vw.setTitle("Button", for: [])
            stackView.addArrangedSubview(vw)
        }
    }
}

However this creates buttons on the left.但是,这会在左侧创建按钮。

在此处输入图像描述

I am not sure how to put them in the center of the screen since the stack view just surrounds the existing views.我不确定如何将它们放在屏幕中央,因为堆栈视图只是围绕现有视图。 Do I put layout constraints on the buttons themselves?我是否对按钮本身设置了布局约束? Or is there an attribute of the stack view like alignment or distribution that I can use?或者是否有堆栈视图的属性,例如 alignment 或我可以使用的分布?

Try give width constraint to the buttons:尝试对按钮进行宽度限制:

for _ in 1 ..< 100 {
        let vw = UIButton(type: UIButton.ButtonType.system)
        vw.setTitle("Button", for: [])
        vw.snp.makeConstraints { make in
            make.width.equalTo(view.frame.width)
        }
        stackView.addArrangedSubview(vw)
    }

Output: Output:

在此处输入图像描述

Adjust the UIStackView to fill UIScrollView width:调整UIStackView以填充UIScrollView宽度:

stackView.snp.makeConstraints { (make) in
     make.edges.equalToSuperview()
     make.width.equalToSuperview()
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM