如何摆脱UIStackView添加的不必要的约束?

时间:2018-11-29 17:10:30

标签: xcode autolayout constraints interface-builder uistackview

我在(垂直)堆栈视图中有一个分段控件,并且希望其前缘和后缘与堆栈视图的左边界和右边界有一定距离。

我尝试定义宽度约束来做到这一点,并尝试了尾随和前导的空间约束,但是在运行时它们被打破,因为系统无法“同时满足约束条件”。从控制台可以很清楚地看到冲突的约束是什么,但是我没有添加(见下图)将分段控件绑定到其UIStackView容器左右边缘的约束,因此我不知道如何摆脱约束其中。系统打破了我要保留的约束。

我应该清楚,我不一定需要UISegmentedControl的宽度限制-尾随和前导的空间限制也可以使用。要明确地说,我需要能够控制分段控件的宽度。

在下面的控制台输出中注意$ WIDTH-SEGCTRL。它来自我在Interface Builder约束中定义的标识符。

2018-11-29 10:43:56.323503-0600 [21479:18697482] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x604000291440 H:[UIStackView:0x7f96373120d0]-(0)-|   (active, names: '|':SectionHeaderView:0x7f9637311e20 )>",
    "<NSLayoutConstraint:0x6040002985b0 H:|-(0)-[UIStackView:0x7f96373120d0]   (active, names: '|':SectionHeaderView:0x7f9637311e20 )>",
    "<NSLayoutConstraint:0x6000004913f0 '$WIDTH-SEGCTRL' UISegmentedControl:0x7f9637312d90.width == 280   (active)>",
    "<NSLayoutConstraint:0x60400029af90 '_UITemporaryLayoutWidth' SectionHeaderView:0x7f9637311e20.width == 320   (active)>",
    "<NSLayoutConstraint:0x604000486720 'UISV-alignment' UIStackView:0x7f96373122d0.leading == UISegmentedControl:0x7f9637312d90.leading   (active)>",
    "<NSLayoutConstraint:0x604000486770 'UISV-alignment' UIStackView:0x7f96373122d0.trailing == UISegmentedControl:0x7f9637312d90.trailing   (active)>",
    "<NSLayoutConstraint:0x604000486680 'UISV-canvas-connection' UIStackView:0x7f96373120d0.leading == UIStackView:0x7f96373122d0.leading   (active)>",
    "<NSLayoutConstraint:0x6040004866d0 'UISV-canvas-connection' H:[UIStackView:0x7f96373122d0]-(0)-|   (active, names: '|':UIStackView:0x7f96373120d0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x6000004913f0 '$WIDTH-SEGCTRL' UISegmentedControl:0x7f9637312d90.width == 280   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

下面是我添加引起问题的宽度约束之前和之后的照片。您会看到Xcode将280宽度约束视为无法执行的事情。它认为分段控件绑定到边缘,但是我不知道为什么。

之前: enter image description here

之后: enter image description here

1 个答案:

答案 0 :(得分:1)

要使用您的堆栈视图布局执行此操作...

对于垂直堆栈视图,设置Alignment: Center

对于水平堆叠视图,将Width设置为等于垂直堆叠视图宽度

对于分段控件,将Width设置为等于-40的“垂直堆栈视图宽度”,这将在每侧保留20点填充。根据自己的喜好调整常数,或将“乘数”设置为0.9,以使分段控件占宽度的90%。

enter image description here