iOS开发之Autolayout

1、概述

在以前的iOS程序中,是如何设置布局UI界面的?

(1)经常编写大量的坐标计算代码

(2)为了保证在3.5 inch和4.0 inch屏幕上都能有完美的UI界面效果,有时还需要分别为2种屏幕编写不同的坐标计算代码(即传说中的“屏幕适配”)

什么是Autolayout

(1)Autolayout是一种“自动布局”技术,专门用来布局UI界面的

(2)Autolayout自iOS 6开始引入,由于Xcode 4的不给力,当时并没有得到很大推广

(3)自iOS 7(Xcode 5)开始,Autolayout的开发效率得到很大的提升

(4)苹果官方也推荐开发者尽量使用Autolayout来布局UI界面

(5)Autolayout能很轻松地解决屏幕适配的问题

Autoresizing

(1)在Autolayout之前,有Autoresizing可以作屏幕适配,但局限性较大,有些任务根本无法完成

(2)相比之下,Autolayout的功能比Autoresizing强大很多

Autolayout2个核心概念:

(1)参照

(2)约束

2Autolayout的警告和错误

警告:

控件的frame不匹配所添加的约束, 比如:

约束控件的宽度为100, 而控件现在的宽度是110

错误:

缺乏必要的约束, 比如:

只约束了宽度和高度, 没有约束具体的位置

两个约束冲突, 比如:

1个约束控件的宽度为100, 1个约束控件的宽度为110

3、代码实现Autolayout

代码实现Autolayout的步骤:

第一步:利用NSLayoutConstraint类创建具体的约束对象

第二步:添加约束对象到相应的view上

- (void)addConstraint:(NSLayoutConstraint *)constraint;

- (void)addConstraints:(NSArray *)constraints;

代码实现Autolayout的注意点:

(1)要先禁止autoresizing功能,设置view的下面属性为NO

view.translatesAutoresizingMaskIntoConstraints = NO;

(2)添加约束之前,一定要保证相关控件都已经在各自的父控件上

(3)不用再给view设置frame

4NSLayoutConstraint

一个NSLayoutConstraint对象就代表一个约束。

创建约束对象的常用方法:

+(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

view1 :要约束的控件

attr1 :约束的类型(做怎样的约束)

relation :与参照控件之间的关系

view2 :参照的控件

attr2 :约束的类型(做怎样的约束)

multiplier :乘数

c :常量

自动布局有个核心公式:

obj1.property1 =(obj2.property2 * multiplier)+ constant value

例如:实现下面效果:

- (void)viewDidLoad

{

[super viewDidLoad];

// 1.添加控件

UIView *blueView = [[UIView alloc] init];

blueView.backgroundColor = [UIColor blueColor];

    blueView.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addSubview:blueView];

UIView *redView = [[UIView alloc] init];

redView.backgroundColor = [UIColor redColor];

    redView.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addSubview:redView];

// 2.约束蓝色

// 2.1.高度

NSLayoutConstraint *blueHeight =

[NSLayoutConstraint constraintWithItem:blueView attribute:

NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:

nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0

constant:40];

[blueView addConstraint:blueHeight];

// 2.2.左边间距

CGFloat margin = 20;

NSLayoutConstraint *blueLeft =

[NSLayoutConstraint constraintWithItem:blueView attribute:

NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:

self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:

margin];

[self.view addConstraint:blueLeft];

// 2.3.顶部间距

NSLayoutConstraint *blueTop =

[NSLayoutConstraint constraintWithItem:blueView attribute:

NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:

self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:

margin];

[self.view addConstraint:blueTop];

// 2.4.右边间距

NSLayoutConstraint *blueRight =

[NSLayoutConstraint constraintWithItem:blueView attribute:

NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:

self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:

-margin];

[self.view addConstraint:blueRight];

// 3.约束红色

// 3.1.让红色右边 == 蓝色右边

NSLayoutConstraint *redRight =

[NSLayoutConstraint constraintWithItem:redView attribute:

NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:

blueView attribute:NSLayoutAttributeRight multiplier:1.0

constant:0.0];

[self.view addConstraint:redRight];

// 3.2.让红色高度 == 蓝色高度

NSLayoutConstraint *redHeight =

[NSLayoutConstraint constraintWithItem:redView attribute:

NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:

blueView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:

0.0];

[self.view addConstraint:redHeight];

// 3.3.让红色顶部 == 蓝色底部 + 间距

NSLayoutConstraint *redTop =

[NSLayoutConstraint constraintWithItem:redView attribute:

NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:

blueView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:

margin];

[self.view addConstraint:redTop];

// 3.4.让红色宽度 == 蓝色宽度 * 0.5

NSLayoutConstraint *redWidth =

[NSLayoutConstraint constraintWithItem:redView attribute:

NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:

blueView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:

0.0];

[self.view addConstraint:redWidth];

}

5、添加约束的规则

在创建约束之后,需要将其添加到作用的view上。

在添加时要注意目标view需要遵循以下规则:

(1)对于两个同层级view之间的约束关系,添加到它们的父view上

(2)对于两个不同层级view之间的约束关系,添加到他们最近的共同父view上

(3)对于有层次关系的两个view之间的约束关系,添加到层次较高的父view上

6VFL语言

什么是VFL语言?

VFL全称是Visual Format Language,翻译过来是“可视化格式语言”,是苹果公司为了简化Autolayout的编码而推出的抽象语言。

7VFL示例

H:[cancelButton(72)]-12-[acceptButton(50)]

canelButton宽72,acceptButton宽50,它们之间间距12

H:[wideView(>[email protected])]

wideView宽度大于等于60point,该约束条件优先级为700(优先级最大值为1000,优先级越高的约束越先被满足)

V:[redBox]-[yellowBox(==redBox)]

竖直方向上,先有一个redBox,其下方紧接一个高度等于redBox高度的yellowBox

H:|-10-[Find]-[FindNext]-[FindField(>=20)]-|

水平方向上,Find距离父view左边缘默认间隔宽度,之后是FindNext距离Find间隔默认宽度;再之后是宽度不小于20的FindField,它和FindNext以及父view右边缘的间距都是默认宽度。(竖线“|” 表示superview的边缘)

8VFL的使用

使用VFL来创建约束数组:

+ (NSArray *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)opts metrics:(NSDictionary *)metrics views:(NSDictionary *)views;

format :VFL语句

opts :约束类型

metrics :VFL语句中用到的具体数值

views :VFL语句中用到的控件

创建一个字典(内部包含VFL语句中用到的控件)的快捷宏定义:

NSDictionaryOfVariableBindings(...)

例如:

NSDictionary *views =

NSDictionaryOfVariableBindings(blueView, redView);

NSArray *conts2 =

[NSLayoutConstraint constraintsWithVisualFormat:

@"V:[blueView(==blueHeight)]-margin-|" options:0 metrics:

@{@"blueHeight" : @40, @"margin" : @20} views:views];

示例代码:

- (void)viewDidLoad

{

[super viewDidLoad];

// 1.添加控件

UIView *blueView = [[UIView alloc] init];

blueView.backgroundColor = [UIColor blueColor];

blueView.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addSubview:blueView];

UIView *redView = [[UIView alloc] init];

redView.backgroundColor = [UIColor redColor];

redView.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addSubview:redView];

// 2.VFL生成约束

NSArray *conts =

[NSLayoutConstraint constraintsWithVisualFormat:

@"H:|-20-[blueView]-20-|" options:0 metrics:nil views:

@{@"blueView" : blueView}];

[self.view addConstraints:conts];

NSArray *conts2 =

[NSLayoutConstraint constraintsWithVisualFormat:

@"V:|-20-[blueView(40)]-20-[redView(==blueView)]" options:NSLayoutFormatAlignAllRight metrics:nil views:@{@"blueView" : blueView, @"redView" : redView}];

[self.view addConstraints:conts2];

NSLayoutConstraint *redWidth =

[NSLayoutConstraint constraintWithItem:redView attribute:

NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:

blueView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:

0.0];

[self.view addConstraint:redWidth];

}}

运行效果图:

9有了AutolayoutUILabel

在没有Autolayout之前,UILabel的文字内容总是居中显示,导致顶部和底部会有一大片空缺区域:

有Autolayout之后,UILabel的bounds默认会自动包住所有的文字内容,顶部和底部不再会有空缺区域:

10基于Autolayout的动画

在修改了约束之后,只要执行下面代码,就能做动画效果:

[UIView animateWithDuration:1.0 animations:^{

[添加了约束的view layoutIfNeeded];

}];

例如:

self.leftMargin.constant = 100;

self.width.constant = 200;

[UIView animateWithDuration:2.0 animations:^{

//父控件和redView都添加了约束

[self.view layoutIfNeeded];

[self.redView layoutIfNeeded];

}];

时间: 2024-08-27 03:22:56

iOS开发之Autolayout的相关文章

iOS开发之autoLayout constraint

前言 ios设备的尺寸越来越多,针对一款app可能要适配到多种设备.多种尺寸.所以.我们期望我们的app可以autoLayout.本文主要介绍在Xcode中使用constraint.未来会不定期对此文进行更新. 约定 本文中view指代从Objuect Library中拖拽出来的各种view 基础 一个view在界面显示,至少有三种决定条件 一.自身大小:如width.height 二.相对于父容器的位置:如固定起始坐标位置或相对位置 三.相对于兄弟view的位置:如顶部对齐.左右距离.堆叠层次

iOS开发之Auto Layout入门

随着iPhone6与iOS8的临近,适配的问题讲更加复杂,最近学习了一下Auto Layout的使用,与大家分享.  什么是Auto Layout? Auto Layout是iOS6发布后引入的一个全新的布局特性,其目的是弥补以往Autoresizing在布局方面的不足之处,以及未来面对更多尺寸适配时界面布局可以更好的适应. 为什么要用Auto Layout? Autolayout能解决不同屏幕(iPhone4,iPhone5,iPad...)之间的适配问题. 在iPhone4时代开发者只需要适

李洪强iOS开发之iOS好文章收集

李洪强iOS开发之iOS好文章收集 该文收集朋友们转发或自己的写的技术文章,如果你也有相关的好文章,欢迎留言,当好文章多的时候,我会对这些好文章进行分门别类 文章 简述 日期 直播服务配置 使用 nginx 和 rtmp 插件搭建视频直播和点播服务器 2015-05-12 20:13:00 iOS9适配技巧 图iOS9适配新技巧 2015-09-29 09:01 TextKit分页效果 图文混排 2015年6月1日 iPhone 6 / 6 Plus 设计·适配方案 屏幕适配 2014-11-2

IOS开发之copy的问题

copy的目的就是修改副本,修改原始对象和副本时不会产生干扰. 定义一个不可变属性A,再定义一个可变属性B.用B做添加删除等操作后再将B赋值给A时,有些人习惯用A = B:其实这样是不安全的. 假设有下面的一段代码: ? 1 2 3 4 5 6 7 8 9 10   int main() {    NSMutableString *strM = [NSMutableString [email protected]"123"];    NSString *str = strM;    N

iOS开发之WKWebView简单使用和常用使用场景

iOS开发之 WKWebVeiw使用 想用UIWebVeiw做的,但是突然想起来在iOS8中出了一个新的WKWebView,算是UIWebVeiw的升级版.本着对新事物的好奇,就上网查了一下,但是找了好多个都没说的多了详细,于是就问谷歌,找文档,看看使用方法,试用了一下,果然不错,记录下来,大家分享! WKWebView的特点: 性能高,稳定性好,占用的内存比较小, 支持JS交互 支持HTML5 新特性 可以添加进度条(然并卵,不好用,还是习惯第三方的). 支持内建手势, 据说高达60fps的刷

iOS开发之CocoaPods的使用

透明色:00ff00ff //设置柱状图的颜色                ColorSet cs = new ColorSet();                cs.Id = "colorset1"; #region 设置柱状图的颜色 待开发                    string strColor = oYAXIS.Color;                    switch (strColor)                    {           

iOS开发之UILabel

UILabel是iOS开发中常用的一个组件,主要用来显示内容. UILabel的主要使用如下: ? 1 2 3 4 5 6 7 8 9 10 /*尺寸*/ CGRect labelRect = CGRectMake(100, 100, 80, 40); /*初始化*/ UILabel *titleLabel = [[UILabel alloc] initWithFrame:labelRect]; /*一些属性的设置*/ titleLabel.font = [UIFont systemFontOf

iOS开发之多XIB之间相互关联

Xib link Xib 1.直接加载xib中的UIView 创建一个View1.xib, 随便设一个背景色,加一个标识UILabel, 这样好知道是这个view是哪一个view. 你可以在这个view上加作意的subview,我只是说明原理,所以这儿并没有加作何subview. 最终我的View1如下图: 由于View1会放到其它View上作为subview,所以这儿size是Freeform, Status Bar是:None. 将下面代码放到viewDidLoad中: &1这行代码就是加载

iOS开发之UISearchBar初探

iOS开发之UISearchBar初探 UISearchBar也是iOS开发常用控件之一,点进去看看里面的属性barStyle.text.placeholder等等.但是这些属性显然不足矣满足我们的开发需求.比如:修改placeholder的颜色.修改UISearchBar上面的UITextfield的背景颜色.修改UITextfield上面的照片等等. 为了实现上述的需求,最好写一个UISearchBar的子类就叫LSSearchBar吧 LSSearchBar.h如下: #import <U