Change width constraint of a Button in StackView Programmatically

2.2k views Asked by At

I have a stackView which contains some UItextfields and one button. I have constrained it in ViewController viewDidLoad like this:

let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.spacing = 40
    stackView.distribution = .fillEqually
    stackView.alignment = .fill
     
     stackView.addArrangedSubview(justAskYouSomeInfosLabel)
     stackView.addArrangedSubview(emailTextField)
     stackView.addArrangedSubview(passwordTextField)
     stackView.addArrangedSubview(againPasswordTextField)
     stackView.addArrangedSubview(registrationButton)
     
     
             //autolayout the stackview
     view.addSubview(stackView)
     stackView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: nil, bottom: nil, trailing: nil, padding: .init(top: 80, left: 0, bottom: 0, right: 0))
     stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
     stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true

Now I want to reduce the width of the button on the bottom of the stackView.

I tried this:

registrationButton.widthAnchor.constraint(equalToConstant: 80).isActive = true

as suggested on other stackOverflow questions but it doesn't work and I receive this error on the console:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 

How can I reduce the width of the button programmatically?

1

There are 1 answers

5
nghiahoang On

from the line stackView.alignment = .fill you agree that the width of subviews of UIStackView has the same width as its parent

Change it as stackView.alignment = .center or stackView.alignment = .leading so that you can set width of button different from its parent.