带两个文本框的约束/自动布局

我试图将两个文本框并排放置,并在旋转设备或更换设备时保持它们的相对宽度/位置。我试图了解约束和自动/布局,但似乎有些混乱。我可以使用一个文本框,但不能使用两个文本框。

Here's what I currently have. enter image description here This is the device in portrait mode. The two textboxes are constrained 20 to the left and right with equal gap of 26 in between of them leaving their width to be 174.

enter image description here

Then when I rotate the device to landscape mode, I get this.. enter image description here

现在,右侧的文本框要比左侧的文本框大得多,并且右侧的约束似乎已更改

enter image description here

While the constraints on the left textbox now appear to be empty.. enter image description here

What I would like is to have the two textboxes keep the gap in between them relative so when I rotate the device either their width scales to match the gap or even if their width doesn't scale then increase the gap between them to match the width.. Something like this enter image description here

约束太令人困惑了:cry:

Edit: Attempt with horizontal stackview enter image description here

但是文本框确实很小。

评论
  • bipsam
    bipsam 回复

    我想您想做的就是也将第一个和第二个元素的宽度相加,使其始终相等。

    以编程方式可以做到这一点。

    在VFL中将是这样的:

    self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[firstElement]-20-[secondElement(==firstElement)]|", // sets the horizontal space
                                                            options: [], 
                                                            metrics: nil,
                                                            views: ["firstElement": textBox1, "secondElement: textBox2]) // sets the reference of the horizontal space
    )
    

    约束将确保两个元素的宽度相同,并且两个元素之间的距离为20 px。

    Using NSLayoutConstraints

    textbox1.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true // sets the textbox 1 and leading of the super view
    textbox2.leadingAnchor.constraint(equalTo: textbox1.trailingAnchor, constant: 20).isActive = true // sets the textbox2 and textbox 1 gap
    textbox2.trailing.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true // sets the textbox 2 and the trailing of the super view
    textbox1.widthAnchor.constraint(equalTo: textbox2.widthAnchor, constant: 0).isActive = true // sets the textbox1 to be of same width as textbox 2
    
    

    IB网点TBH有点令人头疼。我倾向于通过代码完成大部分UI,但也可以在xib中完成,因为我对xib不再了解。

  • id_aut
    id_aut 回复

    如果您摆脱了自动布局,一个简单的解决方案就是

    1)取得水平堆栈视图,对顶部,左侧和底部施加约束,将高度设为44或其他

    2)给你想要的stackview间距,如10

    3)然后将两个文本字段添加到stackview

    4)均匀地设置stackview填充的分布。