iosswiftuiviewstackview

How can I change the height of a single UIView inside of a stackView progromatically?


I'm having trouble figuring out how to have two views have equal heights and the third view have a bigger height than the other two. Right now, whenever I try to change the height of one of the views, it does the same for all other views. Here is what I have...

enter image description here

Any help would be greatly appreciated!

            var line1 = UIView()
            var line2 = UIView()
            var lineText = UIView()
            var lineStackView = UIStackView()
    
            line1.backgroundColor = .red
            line2.backgroundColor = .blue
            lineText.backgroundColor = .orange

            line1.translatesAutoresizingMaskIntoConstraints = false
            line2.translatesAutoresizingMaskIntoConstraints = false
            lineText.translatesAutoresizingMaskIntoConstraints = false
            
            
            line1.heightAnchor.constraint(equalToConstant: 10).isActive = true
            line2.heightAnchor.constraint(equalToConstant: 10).isActive = true
            lineText.heightAnchor.constraint(equalToConstant: 20).isActive = true
            
            lineStackView.distribution = .fillEqually
            lineStackView.axis  = .horizontal
            lineStackView.spacing = 20
            [line1, line2, lineText].forEach{lineStackView.addArrangedSubview($0)}
            view.addSubview(lineStackView)
    
           lineStackView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: nil, trailing: view.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 40.adjusted, bottom: 0, right: 40.adjusted))

Solution

  • Change the .alignment of your stack view:

    lineStackView.alignment = .top
    // or
    lineStackView.alignment = .center
    // or
    lineStackView.alignment = .bottom