如何在堆栈视图中设置按钮的宽度

How to set the width of a button in a stack view

大家好,我正在尝试使用 NSLayoutConstraints 以编程方式设置按钮的宽度。

这是我的按钮:

private let testBtn: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Test", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 28)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = .red

    return button
}() 

这里是我设置堆栈视图及其约束的地方:

fileprivate func setupButton() {
        let ButtonStackView = UIStackView(arrangedSubviews: [ViewBtn])
        ButtonStackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(ButtonStackView)
        
        NSLayoutConstraint.activate([
            ButtonStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100),
            ButtonStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            ButtonStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            ButtonStackView.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

如何调整按钮的宽度并设置为圆角按钮?

谢谢!

以下是添加宽度约束以测试 Button 的方法

 testBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true

圆角你使用

testBtn.layer.cornerRadius = testBtn.bounds.maxY/2

注意:viewDidLayoutSubviews()

中的圆角