Possible to have fine-grained horizontal Auto Layout control in vertical UIStackView?

时间:2018-12-03 12:49:26

标签: ios autolayout uikit uistackview

I'm currently working with a vertical UIStackView in which each view has a UILabel to be displayed on the left and a UIButton to be displayed on the right. The leading constraint for the label should be different than the trailing constraint for the button and the entire view should take up the width of the screen. The alignment for the stackview is fill and the distribution is fillEqually.

enter image description here

The problem I'm running into is that Auto Layout doesn't seem to be respecting the trailing constraint that I'm trying to set for the button on fill alignment (or any other alignment, for that matter). No matter what I put for it, the system sets it to 20. I've tried center, leading, and trailing alignments but they don't work for what I'm trying to do. Is it possible to have the degree of horizontal layout control I'd like with a vertical stackview?

My constraints (radioButton trailing constraint constant is set to 0):

private func sharedInitialization() {
    translatesAutoresizingMaskIntoConstraints = false
    textLabel.translatesAutoresizingMaskIntoConstraints = false
    radioButton.translatesAutoresizingMaskIntoConstraints = false
    addSubview(textLabel)
    addSubview(radioButton)

    NSLayoutConstraint.activate([
        radioButton.widthAnchor.constraint(equalToConstant: 30),
        radioButton.heightAnchor.constraint(equalToConstant: 30),
        radioButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0),
        radioButton.centerYAnchor.constraint(equalTo: centerYAnchor),
        textLabel.trailingAnchor.constraint(equalTo: radioButton.leadingAnchor, constant: -10),
        textLabel.topAnchor.constraint(equalTo: topAnchor, constant: 22),
        textLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
        bottomAnchor.constraint(equalTo: textLabel.bottomAnchor, constant: 22)])
}

Visual debugger: enter image description here

I've looked at Prevent vertical UIStackView from stretching a subview? but that doesn't seem quite applicable to my situation. Thanks in advance for any help!

0 个答案:

没有答案