How to set height of containers in stack view?

只愿长相守 提交于 2019-11-30 09:05:48

'Fill proportionally' distribution type works with intrinsic content size.

So if our vertical stack(height say 600) view has 2 views, ViewA (intrinsic content height 200) and ViewB(intrinsic content height 100), the stack view will size them to ViewA(height 400) and ViewB(height 200).

Also,

  1. If all the views do not have intrinsic content height, vertical stack view will always show an IB error "Needs constraint for: Y position or Height".
  2. Views with no intrinsic height will collapse to zero height.
  3. Views that have intrinsic height will distribute themselves proportionally.

What you really want

is the 'fill' type distribution with two constraints.

  1. ViewA.height = 2* ViewB.height
  2. ViewB.height = 0.5 * ViewC.height

Thats all. Hope it helps.

You could also implement it programmatically where you could eliminate one text field and then return it back with fill equally distribution of stack view, like the following:

class LoginViewController: UIViewController{

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
nameTextField.translatesAutoresizingMaskIntoConstraints = false
emailTextField.translatesAutoresizingMaskIntoConstraints = false
passwordTextField.translatesAutoresizingMaskIntoConstraints = false
}

// IBAction 
@IBAction func registerLoginSegmented(_ sender: Any) {

    if (sender as AnyObject).selectedSegmentIndex == 0{
        // Before we resize (shrink) the nameTextField, change the stackview' distribution from "fill equally" to just "fill"
        stackView.distribution = .fill

        // Change the nameTextField's text
        heightConstraintNameTextField = nameTextField.heightAnchor.constraint(equalToConstant: 0)
        heightConstraintNameTextField?.isActive = true

        // Rearrange the height of the emailTextField
        heightConstraintEmailTextField = emailTextField.heightAnchor.constraint(equalToConstant: 50)
        heightConstraintEmailTextField?.isActive = true

        // Rearrange the height of the passwordTextField
        heightConstraintPasswordTextField = passwordTextField.heightAnchor.constraint(equalToConstant: 50)
        heightConstraintPasswordTextField?.isActive = true

    }
    else {
          // Return the nameTextField by simply trun off the constrants and assign "fillEqually" instead of "fill"
        heightConstraintNameTextField?.isActive = false
        heightConstraintEmailTextField?.isActive = false
        heightConstraintPasswordTextField?.isActive = false
        stackView.distribution = .fillEqually

    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!