[英]Add trailing constraint between two views
I got stuck with a weird behaviour我被一个奇怪的行为卡住了
I added programmatically a trailing constraint between 'UISlider' and 'UILabel', it looks like this:我以编程方式在 'UISlider' 和 'UILabel' 之间添加了一个尾随约束,它看起来像这样:
NSLayoutConstraint *timeLabelTrailing = [NSLayoutConstraint
constraintWithItem:_timeLbl
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_seekBar
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0];
[timeLabelTrailing setActive:true];
[self layoutIfNeeded];
And the 'UILabel' trailing wont match the 'UISlider' trailing.并且“UILabel”尾随与“UISlider”尾随不匹配。
I tried to do the same between the 'UILabel' and the 'UIViewControoler' view and it works just fine, but with the 'UISlider' it goes wrong.我试图在 'UILabel' 和 'UIViewControoler' 视图之间做同样的事情,它工作得很好,但是使用 'UISlider' 就出错了。
Attached some photos from ViewDebugger:附上一些来自 ViewDebugger 的照片:
slider滑块
label标签
It's because you've placed these in a stackview!这是因为你已经把这些放在了一个堆栈视图中! Hence the stackview is suppressing other contraints.因此,stackview 正在抑制其他约束。
How do I know it's getting suppressed?我怎么知道它被压制了?
The viewdebugger is an extremely powerful tool, yet most of its features are unknown. viewdebugger 是一个非常强大的工具,但它的大部分功能是未知的。
The color of the constraints on the right side convey meaning.右侧约束的颜色传达了含义。
FWIW both the gray & black colored constraints are active , yet not every active constraint gets applied . FWIW 灰色和黑色约束都处于活动状态,但并非每个活动约束都得到应用。 eg you could have hundred constraints on the width of a label, each with a different priority.例如,您可以对标签的宽度进行数百个限制,每个限制都有不同的优先级。 While all of them are active, they would get ignored except for the constraint with highest priority.虽然它们都处于活动状态,但除了具有最高优先级的约束之外,它们将被忽略。
As you can see ☝️the label.trailing = self.trailing @1000
is getting ignored.正如你所看到的 ☝️label.trailing label.trailing = self.trailing @1000
被忽略了。 And when you have a priority with '1000' ignored then I'm pretty much sure that debugger is dumping warnings to you, but you didn't mention them in your question.当您忽略“1000”的优先级时,我非常确定调试器正在向您发出警告,但您没有在问题中提及它们。
Long story short when you place things inside a stackview, then you shouldn't be adding much constraints yourself.长话短说,当您将东西放在 stackview 中时,您不应该自己添加太多约束。
I think what you possibly need is我想你可能需要的是
stackView.alignment = .trailing
And make sure you remove the other trailing constraints.并确保删除其他尾随约束。
And if you want your slider to stretch to the full width of the stackview then constrain it to the stackview's width.如果您希望滑块拉伸到 stackview 的整个宽度,则将其限制为 stackview 的宽度。 The label is getting its width from its intrinsicContentSize
and that's fine.标签从其intrinsicContentSize
大小获取其宽度,这很好。
TBH I'm not sure if this is the best approach but I think it works. TBH 我不确定这是否是最好的方法,但我认为它有效。 If anyone knows of a better way then please leave a comment.如果有人知道更好的方法,请发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.