一、实战:构建一个响应式个人资料卡片
UIView *card = [[UIView alloc] init];
card.yoga.isEnabled = YES;
card.yoga.flexDirection = YGFlexDirectionRow;
card.yoga.padding = YGPointValue(10);
card.yoga.alignItems = YGAlignCenter;
UIImageView *avatar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"avatar"]];
avatar.yoga.isEnabled = YES;
avatar.yoga.width = YGPointValue(60);
avatar.yoga.height = YGPointValue(60);
avatar.layer.cornerRadius = 30;
avatar.clipsToBounds = YES;
UIView *infoStack = [[UIView alloc] init];
infoStack.yoga.isEnabled = YES;
infoStack.yoga.flexDirection = YGFlexDirectionColumn;
infoStack.yoga.marginLeft = YGPointValue(10);
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.text = @"小明";
nameLabel.yoga.isEnabled = YES;
UILabel *descLabel = [[UILabel alloc] init];
descLabel.text = @"iOS 开发工程师";
descLabel.yoga.isEnabled = YES;
[infoStack addSubview:nameLabel];
[infoStack addSubview:descLabel];
[card addSubview:avatar];
[card addSubview:infoStack];
[card.yoga applyLayoutPreservingOrigin:YES];
二、性能优化技巧
-
合理使用
applyLayoutPreservingOrigin:,避免重复计算 -
子控件不需要布局的,
isEnabled = NO -
尽量避免嵌套过深的布局结构
-
宽高值建议显式指定,避免 Yoga 无法推导
三、调试 Yoga 布局
NSLog(@"%@", [view.yoga debugDescription]);
四、学习路线建议
| 阶段 | 内容 |
|---|---|
| 提升 | 了解 Yoga 是什么,如何用 |
| 入门 | 理解布局原理和属性 |
| 实战 | 实现实际 UI,优化性能 |