美文网首页
Autolayout自动布局实现的方法二:VFL语言实现约束

Autolayout自动布局实现的方法二:VFL语言实现约束

作者: 南波万_ | 来源:发表于2016-04-18 09:44 被阅读49次

    什么是VFL语言

    • VFL全称是VisualFormatLanguage,翻译过来是“可视化格式语言”

    • VFL是苹果公司为了简化Autolayout的编码而推出的抽象语言


        UIView *blueView = [[UIView alloc] init];
        blueView.backgroundColor = [UIColor blueColor];
        // 不要将AutoresizingMask转为Autolayout的约束blueView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:blueView];
        
        UIView *redView = [[UIView alloc] init];
        redView.backgroundColor = [UIColor redColor];
        // 不要将AutoresizingMask转为Autolayout的约束
        redView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:redView];
        // 间距
        NSNumber *margin = @20;
        // 添加水平方向的约束
        NSString *vfl = @"H:|-margin-[blueView]-margin-[redView(==blueView)]-margin-|";
        NSDictionary *views = NSDictionaryOfVariableBindings(blueView, redView);
        NSDictionary *mertrics = NSDictionaryOfVariableBindings(margin);
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:vfl options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:mertrics views:views];
        [self.view addConstraints:constraints];
        // 添加竖直方向的间距
        NSNumber *height = @40;
        NSString *vfl2 = @"V:[blueView(height)]-margin-|";
        NSDictionary *mertrics2 = NSDictionaryOfVariableBindings(margin, height);
        NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:vfl2 options:kNilOptions metrics:mertrics2 views:views];
        [self.view addConstraints:constraints2];
    
    • 最终效果:

    竖屏效果

    横屏效果

    相关文章

      网友评论

          本文标题:Autolayout自动布局实现的方法二:VFL语言实现约束

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