堆栈上按钮的大小

The size of the button on the stack

我正在尝试在堆栈上设置我自己的按钮大小。 (宽度:350,高度:50)

为了创建一个按钮,我写了一个扩展。 但是由于某种原因,无法在堆栈上创建所需的大小。

我错过了什么?

final class ChooseLanguageView: UIView {
    
    private let ruButton = UIButton.createSystemButton(withTitle: "ru")
    private let enButton = UIButton.createSystemButton(withTitle: "en")
    private let deButton = UIButton.createSystemButton(withTitle: "de")
    
    private lazy var stackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [ruButton,
                                                       enButton,
                                                       deButton])
        stackView.axis = .vertical
       
        return stackView
    }()
    
    private func setupStackView() {
        addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
                stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
                stackView.centerYAnchor.constraint(equalTo: centerYAnchor)
            ])
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .lightGray
        setupStackView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

// MARK: - extension

private extension UIButton {
    
    static func createSystemButton(withTitle title: String) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.backgroundColor = .white
        button.frame.size = CGSize(width: 350, height: 50) // Here I am trying to adjust the size
        
        return button
    }
    
}

结果如下:

您需要添加按钮宽度和高度作为约束

private extension UIButton {
    
    static func createSystemButton(withTitle title: String) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.backgroundColor = .white
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.widthAnchor.constraint(equalToConstant: 350),
            button.heightAnchor.constraint(equalToConstant: 50)
        ])
        return button
    }
    
}