使用autolayout删除和重新添加子视图

时间:2013-06-21 06:12:37

标签: cocoa subview autolayout

当使用自动布局时,我的理解是删除子视图(当然保留对它的引用),删除的子视图仍然知道它的自动布局约束。

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

我认为autolayout会自动调整大小以满足约束条件。那不是这样吗? 我认为自动布局意味着不要弄乱框架。添加子视图时是否仍需要设置初始帧rect,即使是自动布局?

1 个答案:

答案 0 :(得分: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];
}
Autolayout运行时将自动调用

updateConstraints。上面的代码位于UIView的自定义子类中。

你是正确的,在使用Autolayout时,你不想触摸框架尺寸。相反,只需更新updateConstraints中的约束即可。或者,更好的是,设置约束,这样您就不必这样做了。

请参阅我对该主题的回答:

Autolayout UIImageView with programatic re-size not following constraints

您无需设置初始帧。如果您使用initWithFrame,只需将其设置为CGRectZero即可。您的约束将 - 实际上必须 - 详细说明应该有多大的内容,或其他表示运行时可以推断出大小的关系。

例如,如果您的视觉格式为:@"|-[myView]-|",那就是水平维度所需的一切。 Autolayout将知道myView的大小最多为superview所表示的父|的范围。这很酷。