使用YogaKit來做一個(gè)九宮格爆土,看看用它是實(shí)現(xiàn)有多簡單椭懊。
代碼:
//九宮格
- (void)scratchableLatexView {
NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7", nil];
UIView *templateView = [[UIView alloc] initWithFrame:CGRectZero];
templateView.backgroundColor = [UIColor greenColor];
[templateView configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.flexDirection = YGFlexDirectionRow;
layout.height = YGPointValue(40*(arr.count/4));
layout.width = YGPointValue(UI_SCREEN_WIDTH);
layout.flexWrap = YGWrapWrap;
}];
[self.baseClassView addSubview:templateView];
for (NSString *str in arr) {
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = randomColor;
[view configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.width = YGPointValue(UI_SCREEN_WIDTH/4);
layout.height = YGPointValue(40);
}];
[templateView addSubview:view];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectZero];
lbl.text = str;
lbl.textAlignment = NSTextAlignmentCenter;
[lbl configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.flexGrow = 1.0;
layout.padding = YGPointValue(0);
}];
[view addSubview:lbl];
}
[self.baseClassView.yoga applyLayoutPreservingOrigin:NO];
}
效果:
image.png
代碼中的計(jì)算量是不是非常少,都是一些布局的東西步势。這里代碼中最核心代碼就是能換行l(wèi)ayout.flexWrap = YGWrapWrap氧猬,所有的代碼都是圍繞它而轉(zhuǎn)動(dòng)的。
下面就是Flexbox對flex-wrap屬性的介紹坏瘩。
1.2 flex-wrap屬性
默認(rèn)情況下 Flex 跟 LinearLayout 一樣盅抚,都是不帶換行排列的,但是 flex-wrap 屬性可以支持換行排列倔矾。這個(gè)也比 LinearLayout屌了許多妄均。它有三個(gè)值:nowrap柱锹、wrap、wrap-reverse
-
nowrap (默認(rèn)值):不換行
nowrap -
wrap:換行丰包,第一行在上方禁熏。
wrap -
wrap-reverse:換行,第一行在下方邑彪。
wrap-reverse