UIView addSubview自动布局无法正常工作 [英] UIView addSubview auto layout not working

查看:309
本文介绍了UIView addSubview自动布局无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a UIView programatically and add NSLayoutConstraint to it and it works and then add it as a subView of view controller's view. Right now I need to remove this view from superview and some time later add it again. But the layout won't work any more if I add it again using self.view addSubview. How to make the layout works again?

推荐答案

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

You need to take care of some points while adding and removing views from auto layout.

UIView.h中有两种方法 class

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

根据您的要求使用这些方法。所以我建议你什么时候从视图中删除子视图,如果需要更新上级视图的约束。然后调用以下方法来反映布局更改。

Use these methods as per your requirement. So i suggest when ever you remove subview from view, Update constraint of superior view if it is required. And then call below method to reflect layout changes.

[self.view layoutIfNeeded];

大多数情况上面的方法将解决所有与布局相关的问题。但是,如果复杂结构存在,那么我的意思是运行时改变视图的行为。

Most cases above method will solve all layout related issues. However some time if complex structure is there i mean runtime changing behaviour of views.

然后在 UIViewController 中覆盖以下方法,在此方法中执行所有与帧相关的更改。

Then override below method in your UIViewController, Perform all frame related changes in this method.

- (void)viewDidLayoutSubviews

这篇关于UIView addSubview自动布局无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆