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

uch*_*aka 9 cocoa subview autolayout

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

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

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

Max*_*eod 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];
}
Run Code Online (Sandbox Code Playgroud)

updateConstraints将由Autolayout运行时自动调用.上面的代码在你的自定义子类中UIView.

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

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

Autolayout UIImageView与编程重新大小不遵循约束

You don't need to set the initial frame. If you do use initWithFrame, just set it to CGRectZero. Your constraints will - in fact must - detail either how big something should be, or other relationships that mean the runtime can deduce the size.

For example, if your visual format is: @"|-[myView]-|", that's everything you need for the horizontal dimension. Autolayout will know to size myView to be up to the bounds of the parent superview denoted by |. It's pretty cool.