2013-06-21 120 views
9

使用自动布局时,我的理解是删除子视图(当然要保留对其的引用),但删除的子视图仍然知道其自动布局约束。使用自动布局去除和重新添加子视图

但是,稍后将其添加回超级视图时,子视图不再知道其帧大小。相反,它似乎得到一个零框架。

我认为autolayout会自动调整它的大小来满足约束条件。情况并非如此吗? 我认为自动布局意味着不要混淆帧rects。添加子视图时是否仍然需要设置初始框架矩形,即使使用自动布局?

回答

16

删除子视图时,与该子视图相关的所有约束都将丢失。如果您以后需要再次添加子视图,那么您必须再次向该子视图添加约束。

通常,我在我的自定义子视图中创建约束。例如:

-(void)updateConstraints 
{ 
    if (!_myLayoutConstraints) 
    { 
     NSMutableArray *constraints = [NSMutableArray array]; 

     // Create all your constraints here 
     [constraints addWhateverConstraints]; 

     // Save the constraints in an ivar. So that if updateConstraints is called again, 
     // we don't try to add them again. That would cause an exception. 
     _myLayoutConstraints = [NSArray arrayWithArray:constraints]; 

     // Add the constraints to myself, the custom subview 
     [self addConstraints:_myLayoutConstraints]; 
    } 

    [super updateConstraints]; 
} 

updateConstraints将由Autolayout运行时自动调用。上面的代码出现在您的自定义子类UIView中。

你说得对,在与Autolayout合作时,你不想触摸框架尺寸。相反,只需更新updateConstraints中的约束即可。或者,更好的是,设置约束条件,因此您不必这样做。

发现该主题的我的回答:

Autolayout UIImageView with programatic re-size not following constraints

不需要设置初始框架。如果您确实使用initWithFrame,请将其设置为CGRectZero。您的约束将 - 事实上,必须是 - 详细说明应该有多大的东西,或者其他意味着运行时可以推断出大小的关系。

例如,如果您的可视格式为:@"|-[myView]-|",那么这就是横向维度所需的所有内容。 Autolayout将知道尺寸为myView以达到由|表示的父superview的界限。它太酷了。

+1

谢谢。这很好,很清楚。有一点需要注意的是,我问了Cocoa而不是Cocoa-touch,但是对于其他人来说,这些API(如Apple的Peter Ammon所描述的)相同或者几乎相同。两个世界的方法应该是一样的。 – uchuugaka

+1

对不起,我错过了。好点 –

+1

[文档](https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/updateConstraints)说这是**重要**调用'[super updateConstraints]'作为您实现的最后一步。它应该在你的方法的最后,而不是在开始。 – Eric

相关问题