Yoga是facebook開源的一個編寫視圖的跨平臺代碼,YogaKit是用于iOS開發(fā)的。它是基于 Flexbox搞莺,它讓布局變得更簡單∮蟪荩可以用它替代 iOS 的自動布局和 web 的 CSS,也可以將它當(dāng)成一種通用的布局系統(tǒng)使用竖瘾。
Yoga 最初源自 Facebook 在 2014 年的一個開源的 css 布局開源庫沟突,在 2016 年經(jīng)過修改,更名為 Yoga捕传。Yoga 支持多個平臺,包括 Java扩劝、C#庸论、C 和 Swift。
下面就講一下Yoga在iOS開發(fā)中的使用(oc代碼):
使用CocoaPods進(jìn)行安裝:
#這里使用1.5的版本
platform :ios, '8.0'
use_frameworks!
target 'YogaTryout' do
pod 'YogaKit', '~> 1.5'
end
執(zhí)行命令:
pod install
安裝成功提示:
Analyzing dependencies
Downloading dependencies
Installing Yoga (1.5.0)
Installing YogaKit (1.5.0)
Generating Pods project
Integrating client project
[!] Please close any current Xcode sessions and use `YogaTryout.xcworkspace` for this project from now on.
Sending stats
Pod installation complete! There is 1 dependency from the Podfile and 2 total pods installed.
代碼中導(dǎo)入#import <YogaKit/UIView+Yoga.h>
先布局一個試試手
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor redColor];
[view configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.width = YGPointValue(320);
layout.height = YGPointValue(80);
layout.marginTop = YGPointValue(64);
layout.marginLeft = YGPointValue(0);
}];
[self.view addSubview:view];
[view.yoga applyLayoutPreservingOrigin:NO];
看了這個代碼是不是感覺很像Masonry的寫法棒呛,要的就是這種結(jié)果聂示,耐心請往下看。
image.png
我將top和left都給刪掉有什么結(jié)果了
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor redColor];
[view configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.width = YGPointValue(320);
layout.height = YGPointValue(80);
}];
[self.view addSubview:view];
[view.yoga applyLayoutPreservingOrigin:NO];
image.png
正常運行只是默認(rèn)x,y都在起始點簇秒。
再次將代碼簡化
這樣寫大家覺得是否可行了鱼喉?
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor redColor];
[view configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.padding = YGPointValue(self.view.frame.size.width/2);
}];
[self.view addSubview:view];
[view.yoga applyLayoutPreservingOrigin:NO];
image.png
答案是肯定的,還是能運行趋观。padding指的是從x,y的零點開始width和height是設(shè)置值的2倍扛禽。
在開發(fā)布局中有時導(dǎo)航欄偶爾會帶來苦惱,那我能不能在上一個代碼中就添加一個top就可以避開導(dǎo)航欄了皱坛?
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor redColor];
[view configureLayoutWithBlock:^(YGLayout * layout) {
layout.isEnabled = YES;
layout.marginTop = YGPointValue(64);
layout.padding = YGPointValue(self.view.frame.size.width/2);
}];
[self.view addSubview:view];
[view.yoga applyLayoutPreservingOrigin:NO];
image.png
這也是可以的编曼,看到這里了是不是眼中已經(jīng)出現(xiàn)無數(shù)個希望和詩。