📘 第1篇:初识 Yoga —— 布局的利器

1,230 阅读1分钟

一、Yoga 是什么?

Yoga 是 Facebook 开源的跨平台 Flexbox 布局引擎,灵感来自于 Web 的 CSS Flexbox。它被用于 React Native、ComponentKit 等项目中,用于构建灵活响应式的 UI。

二、为什么要用 Yoga?

  • 跨平台(支持 iOS、Android、Windows 等)

  • 布局逻辑清晰(遵循 Flexbox)

  • 性能优越(C++ 实现,OC 有封装)

  • 易集成,易学习

三、如何集成(iOS/Objective-C)?

  1. 使用 CocoaPods 安装:


pod 'yoga', :subspecs => ['Yoga']

  1. 导入头文件:


#import "UIView+Yoga.h"

  1. 启用布局:


view.yoga.isEnabled = YES;

四、基本使用示例


UIView *container = [[UIView alloc] init];

container.yoga.isEnabled = YES;

container.yoga.flexDirection = YGFlexDirectionRow;

container.yoga.justifyContent = YGJustifySpaceBetween;


UIView *leftView = [[UIView alloc] init];

leftView.yoga.isEnabled = YES;

leftView.yoga.width = YGPointValue(100);

leftView.yoga.height = YGPointValue(50);



UIView *rightView = [[UIView alloc] init];

rightView.yoga.isEnabled = YES;

rightView.yoga.width = YGPointValue(100);

rightView.yoga.height = YGPointValue(50);



[container addSubview:leftView];

[container addSubview:rightView];

[container.yoga applyLayoutPreservingOrigin:YES];

五、常用属性简析

属性含义
flexDirection主轴方向(行/列)
justifyContent主轴对齐方式
alignItems交叉轴对齐方式
width / height宽高
margin / padding外边距 / 内边距