iOS开发中利用VFL方法添加约束的基本操作步骤,便于自己查阅

本文介绍如何使用iOS中的UIButton创建三个按钮,并通过Auto Layout进行精确布局。文中详细展示了使用视觉格式语言(VFL)来定义水平和垂直约束的过程。

UIButton *b1 = [UIButton buttonWithType:UIButtonTypeSystem];

    [b1 setTitle:@"确定" forState:UIControlStateNormal];

    b1.backgroundColor=[UIColor lightGrayColor];

    [self.view addSubview:b1];


    UIButton *b2 = [UIButton buttonWithType:UIButtonTypeSystem];

    [b2 setTitle:@"取消" forState:UIControlStateNormal];

    b2.backgroundColor=[UIColor lightGrayColor];

    [self.view addSubview:b2];


    UIButton *b3 = [UIButton buttonWithType:UIButtonTypeSystem];

    [b3 setTitle:@"重试" forState:UIControlStateNormal];

    b3.backgroundColor=[UIColor lightGrayColor];

    [self.view addSubview:b3];


    //预备步骤:关闭自动翻译约束功能

    b1.translatesAutoresizingMaskIntoConstraints = NO;

    b2.translatesAutoresizingMaskIntoConstraints = NO;

    b3.translatesAutoresizingMaskIntoConstraints = NO;

    // 此函数可以自动生成一个Dictionary

    // 将传入的对象引用作为value,将引用名变成字符串作为key

    // 传入的是 (b1,b2,b3)

    // 则生成的字典如下:

    // {@"b1":b1,@"b2":b2,@"b3":b3}

    NSDictionary *diction1 = NSDictionaryOfVariableBindings(b1,b2,b3);

    // vfl式子中的一些特殊含义的数字做一个名称对照表

    NSDictionary *diction2 = @{@"top":@20,@"left":@20,@"right":@20,@"spacing":@10};


    //1.准备一个VFL

    NSString *hVFL = @"|-left-[b1]-spacing-[b2(b1)]-spacing-[b3(b1)]-right-|";

    //2.创建约束

    NSArray *cs1 = [NSLayoutConstraint constraintsWithVisualFormat:hVFL options:NSLayoutFormatAlignAllCenterY metrics:diction2 views:diction1];

    //3.将约束添加到父视图上

    [self.view addConstraints:cs1];


    //创建竖直方向的约束

    NSString *vVFL = @"V:|-top-[b1]";

    NSArray *cs2 = [NSLayoutConstraint constraintsWithVisualFormat:vVFL options:0 metrics:diction2 views:diction1];

    [self.view addConstraints:cs2];


转载于:https://my.oschina.net/iOSBoyJack/blog/509323

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值