iOS 开发学习40 自动布局约束

简介

iOS设备目前有多种屏幕大小。在之前文章里介绍了一些iOS屏幕的尺寸(点击查看)。多样化的屏幕给开发布局带来了一定的困难。约束布局通过描述元素的相对关系来实现自动适配,降低通过代码布局的难度。

方法

第一步要确保story board的Use Autolayout是选中的。
这里写图片描述
约束布局大致有三种方式:

在story board上在手工布局

操作示例:

  • 两个控件设置一样的宽度
    选中要操作的两个控件,然后选择菜单 :
    这里写图片描述
  • 水平居中
    这里写图片描述
    在右下方工具栏也有快捷按钮可以操作:
    这里写图片描述
    或者使用鼠标右键操作:
    这里写图片描述
    当然也可以用鼠标左键+ctrl键拖动控件。

约束类别:

width 宽度固定

height 高度固定

页边距约束 Leading and Trailing space

Leading space to Superview :左边距
Trailing space to Superview :右边距
Top space to Superview:上边距
Bottom space to Superview:下边距

间距约束

Horizontal spacing:水平距离
Vertical Spacing:垂直距离

等宽等高约束

Equal width constraint
Equal height constraint

方向比例约束 Aspect ratio constraint

通过代码添加约束

原型
[NSLayoutConstraint constraintWithItem:(id)item
                             attribute:(NSLayoutAttribute)attribute
                             relatedBy:(NSLayoutRelation)relation
                                toItem:(id)otherItem
                             attribute:(NSLayoutAttribute)otherAttribute
                            multiplier:(CGFloat)multiplier
                              constant:(CGFloat)constant]

枚举值:

typedefNS_ENUM(NSInteger, NSLayoutRelation) {
    NSLayoutRelationLessThanOrEqual = -1,         //小于等于
    NSLayoutRelationEqual = 0,                    //等于
    NSLayoutRelationGreaterThanOrEqual = 1,       //大于等于
};
typedefNS_ENUM(NSInteger, NSLayoutAttribute) {
    NSLayoutAttributeLeft = 1,                    //左侧
    NSLayoutAttributeRight,                       //右侧
    NSLayoutAttributeTop,                         //上方
    NSLayoutAttributeBottom,                      //下方
    NSLayoutAttributeLeading,                     //首部
    NSLayoutAttributeTrailing,                    //尾部
    NSLayoutAttributeWidth,                       //宽度
    NSLayoutAttributeHeight,                      //高度
    NSLayoutAttributeCenterX,                     //X轴中心
    NSLayoutAttributeCenterY,                     //Y轴中心
    NSLayoutAttributeBaseline,                    //文本底标线

    NSLayoutAttributeNotAnAttribute = 0           //没有属性
};

示例:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:note 
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:10]];

可视化的VFL语言添加约束

这个暂时我没有使用,以后再看用法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程圈子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值