Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 以编程方式更改视图尺寸时,“自动布局”似乎不起作用_Iphone_Ios_Uitableview_Autolayout - Fatal编程技术网

Iphone 以编程方式更改视图尺寸时,“自动布局”似乎不起作用

Iphone 以编程方式更改视图尺寸时,“自动布局”似乎不起作用,iphone,ios,uitableview,autolayout,Iphone,Ios,Uitableview,Autolayout,我有一个UITableViewCell的自定义子类,其中设置了一些约束 问题是,当我尝试像这样更改一个视图的大小时: CGRect frm = CGRectMake(0, 0, someValue, 30); cell.indentView.frame = frm; 其他视图(取决于cell.indentView宽度)完全不移动 可能是什么情况 此代码将在以下情况下工作: // enumerate over all constraints for (NSLayoutConstraint *co

我有一个UITableViewCell的自定义子类,其中设置了一些约束

问题是,当我尝试像这样更改一个视图的大小时:

CGRect frm = CGRectMake(0, 0, someValue, 30);
cell.indentView.frame = frm;
其他视图(取决于cell.indentView宽度)完全不移动

可能是什么情况

此代码将在以下情况下工作:

// 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;
    }
}

您必须通知框架进行更新,例如,通过调用
setNeedsLayout
setNeedsUpdateConstraints
layoutifneed

有关正确用法,请参阅文档。

这是因为您不能仅更改具有自动布局约束的对象的框架(因为约束指定位置,而不是手动设置
框架
属性…重新应用约束时,
框架
属性将重置)。请参见松散相关的文章,其中演示了如何正确调整约束以移动视图。(在这种情况下,我们正在制作动画,这不是这里的问题,但它确实演示了如何调整约束以影响
UIView
的移动)

简言之,如果要在autolayout中移动
UIView
,则不能尝试更改
框架,而应调整约束本身。如果您为约束本身创建
IBOutlet
引用,这将简化,此时,您可以调整
NSLayoutConstraint
常量


更新:

Egor建议枚举约束并编辑与所讨论的约束匹配的约束。这非常有效,但就我个人而言,我更喜欢为我想要编辑的特定约束设置一个
IBOutlet
,而不是枚举它们并查找有问题的约束。如果对
indentView
的宽度
NSLayoutConstraint
有一个名为
indentViewWidthConstraint
IBOutlet
,那么您只需:

self.indentViewWidthConstraint.constant = newIndentConstantValue;

自动布局太难看了,我都哭了。快乐编码+1至以上自动布局仇恨者。那是最糟糕的。在将其用于一个比琐碎更难的项目之前,您需要考虑一百次。我最好在一些屏幕上添加几行计算帧的代码。@Rob,最糟糕的是,即使您将部署目标设置为>=iOS 5,它也会自动启动!这对我来说还不够——我必须根据问题和其他答案改变约束条件。