mick1996
mick1996

Reputation: 606

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

Hey guys I am trying to set the width of a button programmatically using NSLayoutConstraints.

Here is my button:

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
}() 

Here is where I set up the stack view and its constraints:

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)
        ])
    }

How can I adjust the width of the button and set it to be a rounded button?

Thanks!

Upvotes: 0

Views: 993

Answers (1)

Jawad Ali
Jawad Ali

Reputation: 14397

Here is how you can add width constrait to testButton

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

to round corners you use

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

Note: round corners in viewDidLayoutSubviews()

Upvotes: 1

Related Questions