我有一个 UITableViewCell 的自定义子类,并设置了一些约束.
I have custom subclass of a UITableViewCell with some constraints set.
问题是当我尝试像这样更改一个视图的大小时:
Problem is when I try to change size of one view like this:
CGRect frm = CGRectMake(0, 0, someValue, 30);
cell.indentView.frame = frm;
其他依赖于 cell.indentView 宽度的视图根本不动.
other views, which depend on cell.indentView width, are not moving at all.
可能是什么情况?
此代码将起作用:
// enumerate over all constraints
for (NSLayoutConstraint *constraint in cell.indentView.constraints) {
// find constraint on this view and with 'width' attribute
if (constraint.firstItem == cell.indentView && constraint.firstAttribute == NSLayoutAttributeWidth)
{
// increase width of constraint
constraint.constant = someValue;
break;
}
}
这是因为你不能只更改具有自动布局约束的对象的框架(因为约束决定了位置,而不是手动设置 frame
properties ... frame
属性将在重新应用约束时重置).请参阅 this 松散相关的帖子,其中展示了它如何正确调整约束以移动视图.(在这种情况下,我们正在制作动画,这不是这里的问题,但它确实演示了如何调整约束以影响 UIView
的移动.)
It's because you cannot just change the frame of an object that has autolayout constraints (because constraints dictate the locations, not manually set frame
properties ... the frame
properties will be reset as constraints are reapplied). See this loosely related post in which it is demonstrated how to properly adjust a constraint to move a view. (In that case, we're animating, which is not the issue here, but it does demonstrate how how one adjusts a constraint to effect the movement of a UIView
.)
简而言之,如果你想在自动布局中移动一个UIView
,你不能试图改变frame
,而要自己调整约束.如果您为约束本身创建 IBOutlet
引用,这将得到简化,此时,您可以调整 NSLayoutConstraint
的 constant
.
In short, if you want to move a UIView
within autolayout, you must not try to change the frame
, but rather adjust the constraints themselves. This is simplified if you create IBOutlet
references for the constraints themselves, at which point, you can adjust the constant
of the NSLayoutConstraint
.
更新:
Egor 建议枚举约束并编辑与所讨论的约束匹配的约束.这很好用,但就个人而言,我更喜欢为我想要编辑的特定约束设置一个 IBOutlet
,而不是枚举它们并寻找有问题的约束.如果您有一个名为 indentViewWidthConstraint
的 IBOutlet
用于 indentView
的宽度 NSLayoutConstraint
,那么您可以简单地:p>
Egor recommended enumerating the constraints and editing the one that matched the one in question. That works great, but personally, I prefer to have an IBOutlet
for the specific constraint I want to edit rather than enumerating them and hunting the one in question. If you had an IBOutlet
called indentViewWidthConstraint
for the width NSLayoutConstraint
of the indentView
, you could then simply:
self.indentViewWidthConstraint.constant = newIndentConstantValue;
这篇关于以编程方式更改视图尺寸时,自动布局似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!