iOS开发 - 屏幕适配之VFL语言

    xiaoxiao2025-03-07  11

    1、简介

    VFL语言是苹果给了简化屏幕适配的工作量推出的一门语言,以不同的方向进行添加约束的

    VFL比纯代码更加的宏观,它在添加约束的同时考虑不同控件之间的关系,纯代码是每个控件单独添加约束

    2、核心

    V 垂直方向  

    H 水平方向

    - 控件之间的间距 如-20-代表间距为20

    []  具体控件 如[view]代表控件view,[view(40)],代表宽度或高度为40

    | 父控件的边缘

    3、代码演示

    需求

    1 黄色控件 + 橙色控件

    2 高度均为40,黄色在做左,橙色在右

    3 两控件之间的水平间距为20

    4 两控件距离屏幕底部间距均为20

    5 黄色控件距离屏幕左侧间距为20,橙色控件距离屏幕右侧间距为20

    关键代码

    UIView *yellow = [[UIView alloc] init]; yellow.backgroundColor = [UIColor yellowColor]; [self.view addSubview:yellow]; UIView *orange = [[UIView alloc] init]; orange.backgroundColor = [UIColor orangeColor]; [self.view addSubview:orange]; yellow.translatesAutoresizingMaskIntoConstraints = NO; orange.translatesAutoresizingMaskIntoConstraints = NO; // constraintsWithVisualFormat:具体约束 // options:约束的方式 // metrics:占位 // 以键值对的形式说明对应的控件 // 1* @{@"yellow" : yellow, @"orange" : orange}]; // 2* NSDictionaryOfVariableBindings(yellow, orange); NSDictionary *metrics = @{@"margin" : @20}; NSDictionary *views = NSDictionaryOfVariableBindings(yellow, orange); NSArray *cons3 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-margin-[yellow]-margin-[orange(==yellow)]-margin-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views]; [self.view addConstraints:cons3]; NSArray *cons4 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[yellow(==yellowHeight)]-margin-|" options:0 metrics:@{@"margin" : @20, @"yellowHeight" : @40} views:views]; [self.view addConstraints:cons4];

    4、总结

    4.1 VFL语言简化的编程的工作量,比起代码更加的宏观

    4.2 VFL语言的格式串,如果写错一个地方就会出现问题,哪怕是少写了一条横线

    4.3  个人建议,如果比较熟练,可以使用纯代码的方式,因为纯代码更加的精细化,容易查错和考虑,因为平铺适配无非就考虑位置和宽高

    4.4 以后会讲解更加简便的屏幕适配方法,如Masonry这个库的使用

    转载请注明原文地址: https://ju.6miu.com/read-1296958.html
    最新回复(0)