我有一个 UITableViewCell 的自定义子类,设置了一些约束。
问题是当我尝试像这样更改一个 View 的大小时:
CGRect frm = CGRectMake(0, 0, someValue, 30);
cell.indentView.frame = frm;
其他取决于 cell.indentView 宽度的 View 根本没有移动。
会是什么情况?
此代码将起作用:
// 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
属性 ... frame
属性将在重新应用约束时重置)。参见 this松散相关的帖子,其中演示了如何正确调整约束以移动 View 。 (在那种情况下,我们正在制作动画,这不是这里的问题,但它确实演示了如何调整约束以影响 UIView
的移动。)
简而言之,如果您想在自动布局中移动 UIView
,您一定不要尝试更改 frame
,而是调整约束本身。如果您为约束本身创建 IBOutlet
引用,这会得到简化,此时,您可以调整 NSLayoutConstraint
的常量
。
更新:
Egor 建议列举约束并编辑与所讨论的约束相匹配的约束。这很好用,但就我个人而言,我更喜欢为我要编辑的特定约束使用 IBOutlet
,而不是枚举它们并寻找有问题的约束。如果你有一个名为 indentViewWidthConstraint
的 IBOutlet
用于 indentView
的宽度 NSLayoutConstraint
,那么你可以简单地:
self.indentViewWidthConstraint.constant = newIndentConstantValue;
关于iphone - 以编程方式更改 View 尺寸时,Autolayout 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14215641/