一、Yoga 的布局流程(底层原理)
Yoga 是基于 树结构 构建的,每个 Node(节点)是一个布局单元,整个布局过程可分为:
-
构建布局树(设置属性)
-
布局计算(递归计算)
-
应用布局(生成坐标并作用于 UI)
二、布局属性详解(Flexbox 思想)
1. flexDirection - 主轴方向
view.yoga.flexDirection = YGFlexDirectionRow;
view.yoga.flexDirection = YGFlexDirectionColumn;
2. justifyContent - 主轴对齐
view.yoga.justifyContent = YGJustifyCenter;
view.yoga.justifyContent = YGJustifySpaceBetween;
3. alignItems - 交叉轴对齐
view.yoga.alignItems = YGAlignStretch;
view.yoga.alignItems = YGAlignCenter;
4. flex - 弹性系数
subview1.yoga.flex = 1;
subview2.yoga.flex = 2;
5. margin / padding
view.yoga.marginTop = YGPointValue(10);
view.yoga.paddingLeft = YGPointValue(5);
三、进阶示例:自适应按钮布局
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.yoga.isEnabled = YES;
button.yoga.flexDirection = YGFlexDirectionRow;
button.yoga.alignItems = YGAlignCenter;
button.yoga.paddingLeft = YGPointValue(10);
button.yoga.paddingRight = YGPointValue(10);
UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon"]];
icon.yoga.isEnabled = YES;
icon.yoga.width = YGPointValue(20);
icon.yoga.height = YGPointValue(20);
UILabel *label = [[UILabel alloc] init];
label.text = @"点击我";
label.yoga.isEnabled = YES;
[button addSubview:icon];
[button addSubview:label];
[button.yoga applyLayoutPreservingOrigin:YES];