1

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 Answers1

4

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.

nghiahoang
  • 538
  • 4
  • 10
  • thanks for the answer I tried it and it actually displays only the button on the center and the other textfields disappear –  Jul 05 '20 at 14:34
  • 1
    I see, other subviews are textField so they have no width. The labels should be fine in this case. So, you need to set the width constraint of textFields as `textField.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true` – nghiahoang Jul 05 '20 at 14:50
  • 1
    You need to define other anchors as well for other UI elements of the StackView. Changing single-width constraint with constant value causing changes in other elements value. – Shashank Mishra Jul 05 '20 at 14:51
  • Thanks, now I used your suggestion and it works. I guessed that there'd be a simpler way to customise just one width, but anyway it works so thank u! :) –  Jul 05 '20 at 15:04
  • You can even set button constraint programmatically so that it will not set to full width. `button.widthAnchor.constraint(equalToConstant: 80.0).isActive = true` – Neeraj Joshi Jul 22 '22 at 12:35