UIView addSubview自动布局不工作

我编程创build了一个UIView,并添加NSLayoutConstraint,它工作,然后将其添加为视图控制器的视图的子视图。 现在我需要从超级视图中删除此视图,并在一段时间后再次添加它。 但是如果使用self.view addSubview再次添加它,布局将不再起作用。 如何使布局再次工作?

在从自动布局中添加和删除视图时,您需要注意一些问题。

UIView.h类中有两种可用的方法

 // Allows you to perform layout before the drawing cycle happens. // -layoutIfNeeded forces layout early - (void)setNeedsLayout; - (void)layoutIfNeeded; 

按照您的要求使用这些方法。 所以我build议,当你从视图中删除子视图,如果需要更新高级视图的约束。 然后调用下面的方法来反映布局的变化。

 [self.view layoutIfNeeded]; 

以上大多数情况下,将解决所有布局相关的问题。 但是,如果复杂的结构有一段时间,我的意思是运行时改变行为的意见。

然后在你的UIViewController覆盖下面的方法,在这个方法中执行所有与帧相关的更改。

 - (void)viewDidLayoutSubviews 

问题是子视图不会inheritance原始视图的大小/框架,并且在那里添加视图,就好像它被卡住在600×600的Any + Any大小中一样。 我的解决scheme是设置原始视图的框架,然后让iOS完成剩余的工作。

 [self.myOtherView setFrame:self.view.frame]; //Replace frame size with already resized view [self.myOtherView setNeedsLayout]; //Tell iOS to autolayout the new sub view [self.addSubView:self.myOtherView]; //Add it 

当您创build约束将其分配给variables

 @property (nonatomic, strong)NSLayoutConstraint *viewConstraintTop; self.viewConstraintTop = [Your Constraint]; 

当你想从超级视图中删除它的约束

 [self.viewConstraintTop autoRemove]; 

删除您的视图,并添加分配约束作为

 self.viewConstraintTop = [Your Constraint];