1.概述

  • 通常我们通过storyboard能够完成的,代码也能够完成,所以这里介绍下代码实现约束的添加,通常我们不这么干(在不使用第三方框架的情况下,使用系统自带的类添加约束特别繁琐),所以这里仅仅简单介绍下代码实现原理

2.实现效果

  • 实现效果 
  • 纯OC代码 
    • 在storyboard中的一条约束在代码中的体现就是一个约束对象,所以添加在storyboard上添加一条约束,相当于创建了一个约束对象并将该约束对象添加到对应的视图上
    • 第一步:创建子控件视图
    • 第二步:禁用子控件的autoresizing属性
    • 第三步:创建约束对象
    • 第四步:添加约束对象
- (void)viewDidLoad {
[super viewDidLoad];
// 1.创建一个子视图,添加到父视图上面
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
#warning 注意点: 如果通过代码来设置Autolayout约束, 那么必须先禁用Autoresizing
// 2.禁用autoresizing
// 2.1给需要设置约束的视图禁用autoresizing,禁用父视图autoresizing对子控件无效
//self.view.translatesAutoresizingMaskIntoConstraints = NO;//错误写法
redView.translatesAutoresizingMaskIntoConstraints = NO; // 3.添加约束
// 3.1红色(红色距离顶部和左边以及右边的边距固定为20,高度固定为50)
// 3.1.1顶部(基于父控件)
/*
constraintWithItem:需要设置约束的view
attribute:需要设置约束的位置
relatedBy:约束的条件
toItem:约束依赖目标
attribute:依赖目标约束位置
multiplier:配置系数
constant:额外需要添加的长度
*/
/*
计算公式:redView.attribute = self.view.attribute * multiplier + constant;
其中:=符号取决于relatedBy:参数
typedef NS_ENUM(NSInteger, NSLayoutRelation) {
NSLayoutRelationLessThanOrEqual = -1, 小于等于
NSLayoutRelationEqual = 0, 等于
NSLayoutRelationGreaterThanOrEqual = 1, 大于等于
};
*/
// 3.1.1.1创建约束对象
NSLayoutConstraint *redTopCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
// 3.1.1.2判断约束条件的层级关系,并添加到对应的视图
[self.view addConstraint:redTopCos];
/*
attribute:传入的是枚举参数
NSLayoutAttributeLeft = 1, 左边距
NSLayoutAttributeRight, 右边距
NSLayoutAttributeTop, 距离顶部边距
NSLayoutAttributeBottom, 距离底部边距
NSLayoutAttributeLeading, 左对齐
NSLayoutAttributeTrailing, 右对齐
NSLayoutAttributeWidth, 宽度
NSLayoutAttributeHeight, 高度
NSLayoutAttributeCenterX, 中点X
NSLayoutAttributeCenterY, 中点Y
NSLayoutAttributeBaseline, 文本底线对齐
*/
// 3.1.2左边约束(基于父控件)
NSLayoutConstraint *redLeftCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
// 3.1.2.2判断约束条件的层级关系,并添加到对应的视图
[self.view addConstraint:redLeftCos]; // 3.1.3右边约束(基于父控件)
NSLayoutConstraint *redRightCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
// 3.1.3.2判断约束条件的层级关系,并添加到对应的视图
[self.view addConstraint:redRightCos]; // 3.1.4 高度约束(自身)
NSLayoutConstraint *redHeightCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:50];
// 3.1.3.2判断约束条件的层级关系,并添加到对应的视图
[redView addConstraint:redHeightCos];
}

  

 

3.VFL语言实现约束的添加

  • 苹果同时为我们提供了VisualFormat语言快速添加约束(使用起来比OC简便一些) 

  • 同样实现上述效果,代码如下:

- (void)viewDidLoad {
[super viewDidLoad];
// 1.创建二个子视图,添加到父视图上面
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView]; UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueView]; #warning 注意点: 如果通过代码来设置Autolayout约束, 那么必须先禁用Autoresizing
// 2.禁用autoresizing
// 2.1给需要设置约束的视图禁用autoresizing,禁用父视图autoresizing对子控件无效
//self.view.translatesAutoresizingMaskIntoConstraints = NO;//错误写法
redView.translatesAutoresizingMaskIntoConstraints = NO;
blueView.translatesAutoresizingMaskIntoConstraints = NO; // 3.添加约束
/*
VisualFormat: VFL语句
options: 对齐方式等
metrics: VFL语句中使用到的一些变量
views: VFL语句中使用到的一些控件
*/
// 3.1红色视图
// 水平方向
NSArray *hCos = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[redView]-20-|" options:kNilOptions metrics:nil views:NSDictionaryOfVariableBindings(redView)];
[self.view addConstraints:hCos]; //竖直方向 NSArray *vCos = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[redView(==50)]" options:kNilOptions metrics:nil views:NSDictionaryOfVariableBindings(redView)];
[self.view addConstraints:vCos]; // 3.2蓝色视图
// 垂直方向
NSArray *vBlueCos = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[redView]-20-[blueView(==50)]" options:NSLayoutFormatAlignAllRight metrics:nil views:NSDictionaryOfVariableBindings(redView,blueView)];
[self.view addConstraints:vBlueCos];
// 水平方向
NSLayoutConstraint *hBlueCos = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:redView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0.0];
[self.view addConstraint:hBlueCos];
/*VFL格式说明
功能        表达式
水平方向       H:
垂直方向       V:
Views        [view]
SuperView      |
关系         >=,==,<=
空间,间隙       -
优先级        @value
*/
}
NSDictionaryOfVariableBindings(redView,blueView) 也相当于:
@{@"redView": redView , @"blueView": blueView} [self.contentView addSubview:self.headerImageViewBackgroundView];
[self.contentView addSubview:self.conversationTitle];
[self.contentView addSubview:self.messageCreatedTimeLabel];
[rightContentView addSubview:self.conversationStatusImageView];
[rightContentView addSubview:self.lastSendMessageStatusView];
[self.contentView addSubview:rightContentView];
[self.contentView addSubview:self.messageTypeLabel];
[self.contentView addSubview:self.messageContentLabel]; self.cellSubViews = NSDictionaryOfVariableBindings(_headerImageViewBackgroundView, _conversationTitle,_messageCreatedTimeLabel, _conversationStatusImageView,_lastSendMessageStatusView,rightContentView,_messageContentLabel,_messageTypeLabel); [self.contentView
addConstraints:
[NSLayoutConstraint
constraintsWithVisualFormat:
@"H:|-portrait_margin_left-[_headerImageViewBackgroundView(width)]-portrait_margin_right-[_"
@"conversationTitle]-5-[_messageCreatedTimeLabel(==40)]-12-"
@"|" options:0 metrics:@{
@"portrait_margin_left" :@(portrait_margin_left),
@"portrait_margin_right" :@(portrait_margin_right),
@"width" :
@([RCIM sharedRCIM].globalConversationPortraitSize.width)
} views:self.cellSubViews]];

  

  

 

利用代码添加autolayout约束的更多相关文章

  1. 使用代码创建AutoLayout约束

    使用代码创建AutoLayout约束 1.代码创建约束的步骤 2.代码创建约束的常用方法 3.代码创建约束的原则 4.禁用Autoresizing的原因 5. 设置相对状态栏的约束,使用self.to ...

  2. iOS代码添加视图约束

    项目要做这样一个效果的启动页. 考虑到版本号是会不断变更的,因此采用动画效果启动页,让版本号动态加载iOS启动页动画效果 - 简书 考虑到屏幕适配问题,因此采用代码对视图添加约束.在添加约束的过程中遇 ...

  3. 代码实现Autolayout

    代码实现Autolayout的步骤 利用NSLayoutConstraint类创建具体的约束对象 添加约束对象到相应的view上 - (void)addConstraint:(NSLayoutCons ...

  4. 【转】iOS学习之Autolayout(代码添加约束) -- 不错不错

    原文网址:http://www.cnblogs.com/HypeCheng/articles/4192154.html DECEMBER 07, 2013 学习资料 文章 Beginning Auto ...

  5. 【转】iOS6中的Auto Layout:通过代码添加约束

        最近做的项目用到了Auto Layout,于是经过了一番大量的google,这是我看到的讲用代码创建约束最清晰的一篇教程,于是想跟更多的人分享一下.原文也比较简单,可以直接过去看,如果我翻译的 ...

  6. 七、eclipse添加离线约束,使不联网也能有一些代码的提示,例如dubbo

    eclipse添加离线约束,使不联网也能有一些代码的提示,例如dubbo 1.将dubbo.xsd文件放到一个无中文目录下 2.eclipse->windows->preferences- ...

  7. 【原】iOS学习之苹果原生代码实现Autolayout和VFL语言

    1.添加约束的规则 在创建约束之后,需要将其添加到作用的view上 在添加时要注意目标view需要遵循以下规则: 1)对于 两个同层级view之间 的约束关系,添加到它们的父view上 2)对于 两个 ...

  8. 史上比较用心的纯代码实现 AutoLayout

    入职有两三个月了吧,都是使用 Objective-C 纯代码(虽然有时候偷偷参杂一些 Swift 开源库)来编写公司APP,写布局的时候几乎都是要么在初始化的时候用 initWithFrame,要么就 ...

  9. 如何优雅的代码编写 AutoLayout

    概述 使用 Objective-C 纯代码编写 AutoLayout,看 AutoLayout 的字面理解就是自动布局,听起来好像蛮屌的样子.说白了就是适配:适应.兼容各种不同的情况,包括不同版本的操 ...

随机推荐

  1. 理解Compressed Sparse Column Format (CSC)

    最近在看<Spark for Data Science>这本书,阅读到<Machine Learning>这一节的时候被稀疏矩阵的存储格式CSC给弄的晕头转向的.所以专门写一篇 ...

  2. new bird in github

    首次使用先要建立本地github信息: git config - -global user.name  newbird git config - -global user.email   newbir ...

  3. java合集框架第一天

    文章目录 1 collection接口 2  list接口 3 Iterator 4 Vertor 5  ArrayList 6 LinkedList 主体部分: (1)collection Java ...

  4. GSM07.10协议中串口复用的注意事项

    DLCI:0通道(地址域中DLCI==0)是控制通道,用来传输管理信息.逻辑通道的建立和关闭,睡眠模式的启动和唤醒,流量控制等控制信息都是用该通道. DLCI:1~n通道是逻辑通道,用来传输用户数据. ...

  5. MVC路由配置例

    public static void RegisterRoutes(RouteCollection routes) { string suffix = string.Empty; routes.Ign ...

  6. runtime 第四部分method swizzling

    接上一篇 http://www.cnblogs.com/ddavidXu/p/5924597.html 转载来源http://www.jianshu.com/p/6b905584f536 http:/ ...

  7. jQuery stop()用法

    jQuery stop()的用法: stop(true)等价于stop(true,false): 停止被选元素的所有加入队列的动画. stop(true,true):停止被选元素的所有加入队列的动画, ...

  8. spring mvc controller间跳转 重定向 传参

    http://blog.csdn.net/jackpk/article/details/19121777/

  9. 部署React+webpack工程的步骤

    # 部署React+webpack工程的步骤ps:以Mac os系统做开发环境.因为npm现在使用灰常的慢,所以我使用淘宝境像cnpm. 1,准备工作: 先确保存已经安装了node.js: 2,文件部 ...

  10. IE7 自动为文件路径添加域名

    对于图片等文件的路径,一般在同一个域名下的文件都会使用相对路径,但如果使用JS获取文件的路径浏览器获取到的路径都是相对路径,但IE7会自动为路径添加域名变成绝对路径... IE7下图片路径,在文件相对 ...