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. WPF学习系列 绘制旋转的立方体

    我是一年经验的web程序员,想学习一下wpf,比较喜欢做项目来学习,所以在网上找了一些项目,分析代码,尽量能够做到自己重新敲出来 第一个项目是 中间的方块会不停的旋转. 第一步,新建wpf项目 第二步 ...

  2. 练习JavaScript实现梯形乘法表

    效果: 表格用html中的table,tr,td,然后利用for语句实现,循环输出行和列,再根据行列的数量进行乘法运算,第一个for循环输出9行,然后内嵌一个for,在条件表达式中取第一个for循环的 ...

  3. POJ 1149 PIGS

    PIGS Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 20579   Accepted: 9387 Description ...

  4. sql查询,不在某一范围问题的新思路

    新思路: A为学生表 B为中间表(学生和课程的) C为课程表 新的思路是用left join,(right join应该也可以) 查询没有选课的学生 ... C left join B on A.si ...

  5. bzoj1415[NOI2005]聪聪和可可

    之前做的一些图上的期望步数的题大多用到高斯消元来求解(HNOI游走,SDOI走迷宫,etc),因此我一开始做这道题的时候想偏了- 这道题的性质:聪聪和可可之间的最短路长度严格递减.因为聪聪总可以多走一 ...

  6. git 远程仓库

    1.查看当前的远程库 git remote git remote -v 2.添加远程仓库 git remote add [shortname] [url] 3.从远程仓库抓取数据 git fetch ...

  7. easyUI combobox 控件 使用

    1,combobox 二级联动 (参数传递 函数调用) // toolbar 学校班级二级联动 var paramSearch = { school : $('#search-school'), cl ...

  8. excel批处理_判断一个名称是不是药品

    把药品名称导入到sheet1的A字段 # -*- coding: utf-8 -*-"""Created on Fri Dec  9 09:38:58 2016判断一个名 ...

  9. K-Means clusternig example with Python and Scikit-learn(推荐)

    https://www.pythonprogramming.net/flat-clustering-machine-learning-python-scikit-learn/ Unsupervised ...

  10. JS,删除数据时候,多次确认后才删除。

    function delfun(){ if(window.confirm("请仔细核对无误,删除本数据后不能恢复.")){ if(window.confirm("请再次确 ...