选择stackView上将拉伸的子视图(以编程方式)

时间:2019-01-21 17:16:34

标签: ios swift uistackview

我有一个水平堆栈视图的显示,该子视图由一个标签和一个textField组成。 stackView受到视图边界的限制

我正在尝试将textField子视图拉伸到,以便它填充堆栈的剩余空间,同时标签的堆栈会进行调整以适合标签本身的大小。但是相反的情况正在发生。我尝试了许多解决方案,但没有任何帮助。所有的视图和约束都是通过编程实现的。

对于我的堆栈,我正在使用:

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
}

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)

结果: https://imgur.com/a/ccFZlRM

请注意,这正是我想要实现的目标。但我想将textField拉伸。

1 个答案:

答案 0 :(得分:0)

contentHuggingPriority设置为label,以使其始终保持其内容大小,而textField占用剩余空间。

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