美文网首页iOS
iOS-Autolayout-VFL

iOS-Autolayout-VFL

作者: 七月上 | 来源:发表于2016-04-20 20:58 被阅读136次

    在开发过程中难免会遇到自动布局方面的问题,VFL就是自动布局的一种方法。
    VFL:Visual Format Language 可视化格式语言

    自动布局.gif

    使用VFL简单分为三个步骤:
    1.禁用translatesAutoresizingMaskIntoConstraints

    translatesAutoresizingMaskIntoConstraints属性和autolayout有关,如果你定义的view想要使用autolayout,就将translatesAutoresizingMaskIntoConstraints设为NO,如果你使用的不是autolayout,就将translatesAutoresizingMaskIntoConstraints设为YES。

    //为了方便封装了一个创建view的方法
    -(UIView *)createView:(NSString *)view addToView:(UIView *)sView{
    
        UIView *myView = [[NSClassFromString(view) alloc]init];
        myView.translatesAutoresizingMaskIntoConstraints = NO;
        [sView addSubview:myView];
    
        return myView;
    }
    
        UIView *view1 = [self createView:@"UIView" addToView:self.view];
        view1.backgroundColor = [UIColor redColor];
        UIView *view2 = [self createView:@"UIView" addToView:self.view];
        view2.backgroundColor = [UIColor brownColor];
    

    2.绑定视图和字符串

    
    
    NSDictionary *views = NSDictionaryOfVariableBindings(view1,view2)
    

    3.添加约束
    NSLayoutConstraint约束的类
    constraintsWithVisualFormat:VFL语句
    options:基于哪一个选项(基于哪个方向去计算布局)
    metrics:绑定数值与字符串
    views:绑定视图 与字符串

    
    
      中国语言
         view1:
         横向:距离父视图左侧100 view1宽度最小是100 距离父视图右侧是100
         竖向:距离父视图顶部150 view1的高度是40
      可视化语言
         view1:
         H:|-100-[view1(>=100)]-100-|
         V:|-150-[view1(40)]
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[view1(>=100)]-100-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-150-[view1(40)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
    
    
     view2:
         横向:距离父视图左侧100 view2宽度最小是100 距离父视图右侧是100
         竖向:距离view1 50 view2的高度和view1相同
     view2:
         H:|-100-[view1(>=100)]-100-|
         V:[view1]-50-[view2(view1)]
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[view2(>=100)]-100-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view1]-50-[view2(view1)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
    

    相关文章

      网友评论

        本文标题:iOS-Autolayout-VFL

        本文链接:https://www.haomeiwen.com/subject/xyxtrttx.html