iOS 自动布局 Auto Layout 入门 01 背景介绍

来源:互联网 发布:Linux下重启apache 编辑:程序博客网 时间:2024/06/04 18:21

如果你在考虑如何让我们的app在手机处于水平和垂直的情况下都保持很好的布局?如何让我们的程序很好的同时支持iPhone和iPad?请使用自动布局-Auto Layout!

转载请注明出处:http://blog.csdn.net/yamingwu/article/details/44120513

我们将使用几节的篇幅进行自动布局的入门讲解。Let's start!

Springs和Struts的问题

Autosizing maks也称为Springs and struts模型用于确定当view的父view发生大小变化时,该view如何进行响应。这个view的边界是可扩展的还是固定的(struts)?这个view的长和宽需要进行变化吗(springs)?在简单的场景下,autosizing系统工作ok,但是当布局比较复杂时,就不行了。下面我们通过一个实例,来看看springs和struts的问题。

打开xcode,创建名为StrutsProblem的single view应用程序并disable掉自动布局:


添加3个view到view controller中,上边两个view大小为130宽,200高,下面一个view大小为280宽,200高。各个view之间的间隔为20。


编译执行程序,rotate模拟器,效果如下,这并不是我们所期望的效果:


如下所示修改这3个view的autosizing mask,看看效果如何?

左上角view,让其粘在父view的左上角,在父view改变大小时,修改自己的大小。


右上角view:


下面的view:


编译执行,旋转手机后,效果如下:


接近我们所期望的效果了,但是view之间的间距明显不正确。问题的根源在于autosizing masks在父view发生变化时,通知子view要进行对应的变化,但是它无法告诉子view,要进行多少变化。要基于autosizing来解决这个问题必须通过写一些代码来实现。

在设备发生旋转之前,过程中和结束后UIKit都会发送相应的消息给我们的View Controller。我们可以通过解析这些消息,来改变view的布局,这里我们需要重载willAnimateRotationToInterfaceOrientation:duration:方法。

创建3个view的outlet:

@property (weak, nonatomic) IBOutlet UIView *topLeftView;@property (weak, nonatomic) IBOutlet UIView *topRightView;@property (weak, nonatomic) IBOutlet UIView *buttonView;

添加以下代码到ViewController.m中:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];        if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft        || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)    {        CGRect rect = self.topLeftView.frame;        rect.size.width = 210;        rect.size.height = 120;        self.topLeftView.frame = rect;                rect = self.topRightView.frame;        rect.origin.x = 250;        rect.size.width = 210;        rect.size.height = 120;        self.topRightView.frame = rect;                rect = self.bottomView.frame;        rect.origin.y = 160;        rect.size.width = 440;        rect.size.height = 120;        self.bottomView.frame = rect;    }    else    {        CGRect rect = self.topLeftView.frame;        rect.size.width = 130;        rect.size.height = 200;        self.topLeftView.frame = rect;                rect = self.topRightView.frame;        rect.origin.x = 170;        rect.size.width = 130;        rect.size.height = 200;        self.topRightView.frame = rect;                rect = self.bottomView.frame;        rect.origin.y = 240;        rect.size.width = 280;        rect.size.height = 200;        self.bottomView.frame = rect;    }}
这段代码的作用是在设备发生旋转时,根据设备是要旋转到横向还是纵向,相应的调整3个view的位置和大小。在编译运行前,需要修改3个view的Autosizing mask,否则autosizing机制会和我们的代码相冲突。


编译并运行,程序执行效果和我们所期望的一致,但是,这也太麻烦了吧!


下一节,我们将使用AutoLayout来解决同样的问题。


0 0
原创粉丝点击