如何在堆栈视图中设置容器的高度?

时间:2015-12-02 17:47:12

标签: objective-c swift autolayout uicontainerview uistackview

我想问你是否可以设置垂直堆栈视图中每个容器的百分比高度?我想在堆栈视图中有3个容器。首先应该占屏幕尺寸的40%,第二个占20%,第三个占40%。谢谢

enter image description here

2 个答案:

答案 0 :(得分:11)

'按比例填写'分发类型使用内在内容大小

因此,如果我们的垂直堆栈(高度说600)视图有2个视图,ViewA(内部内容高度200)和ViewB(内部内容高度100),堆栈视图将它们调整为ViewA(高度400)和ViewB(高度) 200)。

另外,

  1. 如果所有视图都没有内在内容高度,则垂直堆栈视图将始终显示IB错误"需要约束:Y位置或高度"。
  2. 没有固有高度的视图将折叠到零高度。
  3. 具有固有高度的视图将按比例分配。
  4. 你真正想要的是什么

    ' fill'类型分布有两个约束。

    1. ViewA.height = 2 * ViewB.height
    2. ViewB.height = 0.5 * ViewC.height
    3. 多数民众赞成。希望它有所帮助。

      enter image description here

答案 1 :(得分:0)

您还可以通过编程方式实现它,您可以在其中删除一个文本字段,然后使用填充均匀分布的堆栈视图将其返回,如下所示:

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

    }

}