Lucas Mathielo
Lucas Mathielo

Reputation: 33

Choose which subview on a stackView will stretch (Programmatically)

I have a display of horizontal stack views, which subviews consists on a label and a textField. the stackView is constrained with the borders of the view

I'm trying to stretch my textField subview to so it fills the remaining space of the stack, while the label's stacks adjusts to fit the label size itself. But the inverse is happening. I've tried many solutions but nothing helped me. All the views and constraints we're made programmatically.

For my stack, I'm using:

func customTextField() -> UIStackView {

    let stack: UIStackView = {
        let sv = UIStackView()
        sv.axis = .horizontal
        sv.isLayoutMarginsRelativeArrangement = true
        sv.alignment = .leading
        sv.backgroundColor = .red
        sv.translatesAutoresizingMaskIntoConstraints = false
        return sv
    }()


    let label: UILabel = {
        let lb = UILabel()
        lb.backgroundColor = .red
        lb.text = "Label is here"
        lb.translatesAutoresizingMaskIntoConstraints = false
        return lb
    }()

    let textField: UITextField = {
        let tf = UITextField()
        tf.backgroundColor = .blue
        tf.text = "Text Field"
        tf.translatesAutoresizingMaskIntoConstraints = false
        return tf
    }()


    stack.addArrangedSubview(label)
    stack.addArrangedSubview(textField)
    return stack
}

the caller of my customTextField:

    let profileUserStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 8
        stack.contentMode = .scaleToFill
        stack.translatesAutoresizingMaskIntoConstraints = false
        return stack
    }()
    self.addSubview(profileUserStack)

    for i in profileTextViews {
        let view = self.customTextField()
        profileUserStack.addArrangedSubview(view)
    }

    constraints.append(profileUserStack.buildConstraint(toItem: perfilImageView, constant: 32, type: .top, baseItem: .bottom))

    constraints.append(profileUserStack.buildConstraint(toItem: self, constant: 16, type: .leading, baseItem: .leading))

    constraints.append(profileUserStack.buildConstraint(toItem: self, constant: -16, type: .trailing, baseItem: .trailing))

    activateConstraints(&constraints, to: self)

The results: https://i.sstatic.net/WTfQK.jpg

Notice that's exactly what I want to achieve. But I want the textField to be stretched.

Upvotes: 3

Views: 1968

Answers (1)

Sandeep
Sandeep

Reputation: 21144

Set contentHuggingPriority to your label such that it always stays as the size of its content and textField takes remaining space.

label.setContentHuggingPriority(.defaultHigh, for: .horizontal)

Upvotes: 4

Related Questions