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. 记录在linux下的wine生活

    记录在linux下的windows生活 本篇内容涉及QQ.微信.Office的安装配置 QQ: 到deepin下载轻聊版. 如果安装了crossover,那么将其中opt/cxoffice/suppo ...

  2. BZOJ-2127-happiness(最小割)

    2127: happiness(题解) Time Limit: 51 Sec  Memory Limit: 259 MBSubmit: 1806  Solved: 875 Description 高一 ...

  3. 蓝牙4.0(BLE)开发

    转载请注明出处 http://blog.csdn.net/pony_maggie/article/details/26740237 作者:小马 IOS学习也一段时间了,该上点干货了.前段时间研究了一下 ...

  4. PHP编码规范PSR-2

    .note-content { font-family: "Helvetica Neue", Arial, "Hiragino Sans GB", STHeit ...

  5. qrcode 生成验证码带文字

    /** * 生成二维码 * * @param int $id * @param string $file * @param boolean $is_download */public function ...

  6. Spring MVC学习笔记——登录和异常处理

    1.在WEN-INF文件夹下面,添加一个login.jsp文件 <%@ page language="java" contentType="text/html; c ...

  7. mysql myisam简单分表设计

    一般来说,当我们的数据库的数据超过了100w记录的时候就应该考虑分表或者分区了,这次我来详细说说分表的一些方法.目前我所知道的方法都是MYISAM的,INNODB如何做分表并且保留事务和外键,我还不是 ...

  8. Struts2返回json格式数据踩坑记录

    事件起因 昨天提测修改冻结/解冻银行卡样式的功能,微姐测试过程中发现调用ajax请求耗时过长,今天来排查,发现浏览器请求/finance/ajax/freeze/ajaxGetShopLists时,对 ...

  9. .htaccess语法之RewriteCond与RewriteRule指令格式详细解释

    htaccess语法之RewriteCond与RewriteRule指令格式详细解释 (2012-11-09 18:09:08) 转载▼ 标签:  htaccess it 分类: 网络 上文htacc ...

  10. MySQL主从复制实现

    上回提到了用ThinkPHP框架来实现数据库的读写分离,现在就来简单说说MySQL的主从复制. 形式 一主一从(也就是这里要实现的形式) 主主复制 一主多从 多主一从(MySQL5.7开始支持) 联级 ...