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. Jetson ARM SeetaFace编译

    SeetaFace简介 SeetaFace依赖于OpenCV,对于Tegra on Ubuntu,Nvidia提供libopencv4tegra并且可以使用Cuda加速. 准备工作 1.阅读OpenC ...

  2. python爬乌云dorps文章

    有时候翻看drops 无赖drops没有一个全部文章列表,所以就有了这个想法把所有文件标题链接都爬出来这样又直观又好找感兴趣的文章 #coding=utf-8 import re import url ...

  3. Android 天猫apk聊天数据库解密

    1.使用Android 天猫apk 进行聊天会产生tmallWangXinDB的数据库.2.用sqlite3 工具打开提示加密或者错误.3.需要对该数据库进行解密. 解密流程:1.反编译apk,dex ...

  4. JavaScript系列文章:详解正则表达式之二

    在上一篇文章中我们讲了正则表达式的基本用法,接下来博主想聊聊其中的细节,今天就从正则修饰符开始吧. 正则修饰符又称为正则标记(flags),它会对正则的匹配规则做限定,进而影响匹配的最终结果.在上次的 ...

  5. 查看Mysql版本号 (最简单的是status )

    一.使用命令行模式进入mysql会看到最开始的提示符;二.命令行中使用status可以看到;三.使用系统函数等等,   查看版本信息 #1使用命令行模式进入mysql会看到最开始的提示符 Your M ...

  6. jsp URL中文传值

    js中,讲中文转码 encodeURI(中文): Java中,转回中文 java.net.URLDecoder.decode(乱码,"utf-8"): 例子; window.loc ...

  7. layer——源码学习

    一.根据源码的学习 发现创建弹窗:使用了一些div来组成 zindex 和 index 是自动生成. zindex 表示生成的层次关系 index 用来表示各个层的id 默认class名 h = [& ...

  8. [慢查优化]建索引时注意字段选择性 & 范围查询注意组合索引的字段顺序

    文章转自:http://www.cnblogs.com/zhengyun_ustc/p/slowquery2.html 写在前面的话: 之前曾说过"不要求每个人一定理解 联表查询(join/ ...

  9. 的vim和emacs常用配置记录

    因为经常改变工作环境,所以在这里记录一下我的.vimrc文件和.emacs文件的内容. vimrc的配置文件,主要是设置语法高亮,和tab键的宽度,个人喜欢设置为4个空格的分量. " set ...

  10. 一款强大的Android网络渗透软件dsploit

    dSploit是一款基于Android系统的功能十分全面强大的网络渗透工具,可以提供给网络安全工作人员检查网络的安全性.小黑这次主要使用了其中的"简易嗅探""会话劫持&q ...