无法在 UIstackview 中居中元素?

Not able to centre elements in UIstackview?

我正在做一个现场游乐场项目,我以编程方式创建了所有内容,但我无法将 stackView 中的按钮对齐到中心,请帮助我 这是主要游乐场的代码

import PlaygroundSupport
import UIKit
let vc = HomeViewController()
let navController = UINavigationController(rootViewController: vc)
navController.view.frame = CGRect(x: 0, y: 0, width: 600, height: 600)

PlaygroundPage.current.liveView = navController

这是我的 HomeVC 代码


import UIKit

public class HomeViewController:UIViewController{
    let stackView:UIStackView = {
       let st = UIStackView()
        st.axis = .horizontal
        st.alignment = .center
        st.distribution = .fillEqually
        st.backgroundColor = .cyan
        st.spacing = 10
        st.translatesAutoresizingMaskIntoConstraints = false
        
       return st
    }()
    let generateButton:UIButton = {
       let btn = UIButton()
        btn.setTitle("Generate Array", for: .normal)
        btn.backgroundColor = .yellow

        btn.translatesAutoresizingMaskIntoConstraints = false
        return btn
    }()
    let generateButton2:UIButton = {
       let btn = UIButton()
        btn.setTitle("Generate 2", for: .normal)
        btn.backgroundColor = .brown

        btn.translatesAutoresizingMaskIntoConstraints = false
        return btn
    }()
    
    public override   func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemPink
        view.addSubview(stackView)
        
        stackView.addArrangedSubview(generateButton)
        stackView.addArrangedSubview(generateButton2)

        
        stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        stackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        stackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        stackView.heightAnchor.constraint(equalToConstant: 120).isActive = true
    }
}


我只想将堆栈视图中的按钮对齐到中心.....请帮助我

您的按钮正确居中,UINavigationBar 给您一种错误的错觉。要解决此问题,您有几种选择:


隐藏导航栏:

navigationController?.setNavigationBarHidden(true, animated: false)

移除导航栏半透明:

navigationController?.navigationBar.isTranslucent = false

edgesForExtendedLayout设为空数组(Source):

edgesForExtendedLayout = []

所有这些操作都可以在 viewDidLoad() 函数中执行。