iOS开发之纯代码约束
2015-12-30 15:57
501 查看
我们在平时开发中, 大多数的控件都需要进行约束, 约束的方法比较多, 例如autolayout等. 今天我们就来谈谈如何进行纯代码约束.
首先我们来说第一种情况, 假如我们有一个label叫namelabel, 现在我们需要让namelabel距离self.view的上边距100, 距离左边距20.那么我们用纯代码需要这样写.
这样就加上了namelabel的约束, 这三句代码就可以让namelabel距离左边距20 距离上边距100.
还有一种是需要给namelabel一个宽度和高度, 假如和self.view同高同宽.
这三句代码就可以给namelabel一个宽度和高度, 分别是和self.view的宽度和高度相等.
这样就完成了基本的纯代码约束, 是不是很简单呢.
首先我们来说第一种情况, 假如我们有一个label叫namelabel, 现在我们需要让namelabel距离self.view的上边距100, 距离左边距20.那么我们用纯代码需要这样写.
// 左 NSLayoutConstraint * nameLabelLeading = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20.f]; // 上 NSLayoutConstraint * nameLabelTop = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:0.1f constant:100.f]; [self.view addConstraints:@[nameLabelLeading,nameLabelTop]];
这样就加上了namelabel的约束, 这三句代码就可以让namelabel距离左边距20 距离上边距100.
还有一种是需要给namelabel一个宽度和高度, 假如和self.view同高同宽.
// 宽 NSLayoutConstraint * nameLabelWidth = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:self.view.bounds.size.width]; // 高 NSLayoutConstraint * nameLabelHeigth = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:self.view.bounds.size.height]; [self.view addConstraints:@[nameLabelHeigth,nameLabelWidth]];
这三句代码就可以给namelabel一个宽度和高度, 分别是和self.view的宽度和高度相等.
这样就完成了基本的纯代码约束, 是不是很简单呢.
相关文章推荐
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- flex 控件的重要属性
- Delphi控件ListView的属性及使用方法详解
- web下载的ActiveX控件自动更新
- WinForm实现按名称递归查找控件的方法
- C#中父窗口和子窗口之间控件互操作实例
- Android编程之Button控件用法实例分析
- Android控件之CheckBox、RadioButton用法实例分析
- MFC中动态创建控件以及事件响应实现方法
- WinForm自定义函数FindControl实现按名称查找控件
- Android控件之ProgressBar用法实例分析
- WinForm拖拽控件生成副本的解决方法
- ASP.NET动态添加用户控件的方法
- ASP.NET的HtmlForm控件学习及Post与Get的区别概述