您的位置:首页 > 移动开发 > IOS开发

iOS AutoLayout

2015-11-16 00:00 435 查看
摘要: iOS自动布局

1. 自动布局可以使用 InterfaceBuilder 生成,也可以手动写代码生成。

2. 代码生成自动布局时可以使用 NSLayoutConstraint 类,也可以使用 Lyt 或 Masonry 等自动布局框架来完成,参见 自动布局框架介绍

3. 对 UIView 使用自动布局时需要设置 translatesAutoresizingMaskIntoConstraints 属性为 NO,否则自动布局无效。

示例如下:

UILabel *title = [[UILabel alloc] initWithFrame:CGRectZero];
title.translatesAutoresizingMaskIntoConstraints = NO;
title.font = [UIFont systemFontOfSize:16];
title.textColor = [UIColor whiteColor];
title.textAlignment = NSTextAlignmentCenter;
title.text = @"测试内容";
[self.view addSubview title];
[title lyt_alignToParentWithMargin:20];
[title lyt_alignLeftToParent];
[title lyt_alignRightToParent];
[self.view addConstraint:[title lyt_constraintBySettingHeight:21]];

4. 自动布局时尽量不要使用常量定义 UIView 的宽高和位置,否则在不同分辨率下无法自适应。

5. 使用 Leading Space 和 Trailing Space 确定 UIView 的宽度时要求做为参考对象的 UIView 必须有固定的宽度,否则无法确定该 UIView的宽度,例如:在 UIView 中添加 UIScrollView(宽度占满UIView),在UIScrollView上添加UIButton,UIButton以UIScrollView为参考对象设置 Leading Space 和 Trailing Space 后并不能确定UIButton的宽度,需要UIButton以UIView为参考对象设置 Leading Space 和 Trailing Space才能确定UIButton的宽度,该规则对于高度同样适用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息