编程技术记录

世界你好!

目录

集成

Yoga是Facebook开源的基于CSS FlexBox布局框架,核心使用C++实现的,在iOS上并不需要直接集成C++代码,只需通过CocoaPod引入YogaKit(间接集成C++代码)

# Podfile

platform :ios, '8.0'
use_frameworks!

target "TestProject" do
    pod 'YogaKit'
end

使用

集成后,YogaKit提供了UIView的方法扩展

// UIView+Yoga.h
@property (nonatomic, readonly, strong) YGLayout *yoga;

yoga类型为YGLayout,描述了UIView如何布局。

简单示例


//代码源自 https://www.jianshu.com/p/95bf92143141
-(void)test
{

    [self.view configureLayoutWithBlock:^(YGLayout * layout) {
        layout.isEnabled = YES;
        layout.width = YGPointValue(self.view.bounds.size.width);
        layout.height = YGPointValue(self.view.bounds.size.height);
        layout.alignItems = YGAlignCenter;
    }];

    UIView *contentView = [[UIView alloc]init];
    contentView.backgroundColor = [UIColor lightGrayColor];
    [contentView configureLayoutWithBlock:^(YGLayout * layout) {
        layout.isEnabled = true;
        // 4
        layout.flexDirection =  YGFlexDirectionRow;
        layout.width = YGPointValue(320);
        layout.height = YGPointValue(80);
        layout.marginTop = YGPointValue(100);

        layout.padding =  YGPointValue(10);//设置了全部子项目的填充值
    }];

    UIView *child1 = [[UIView alloc]init];
    child1.backgroundColor = [UIColor redColor];
    [child1 configureLayoutWithBlock:^(YGLayout * layout) {
        layout.isEnabled = YES;
        layout.width = YGPointValue(80);
        layout.marginRight = YGPointValue(10);
    }];

    UIView *child2 = [[UIView alloc]init];
    child2.backgroundColor = [UIColor blueColor];
    [child2 configureLayoutWithBlock:^(YGLayout * layout) {
        layout.isEnabled = YES;
        layout.width = YGPointValue(80);
        layout.flexGrow = 1;
        layout.height = YGPointValue(20);
        layout.alignSelf = YGAlignCenter;

    }];

    [contentView addSubview:child1];
    [contentView addSubview:child2];
    [self.view addSubview:contentView];
    [self.view.yoga applyLayoutPreservingOrigin:YES];
}

注意:

无特殊情况,方法applyLayoutPreservingOrigin最好由根节点执行

© Beli. All Rights Reserved.