Integrating Flexbox with Autolayout on iOS
Flexbox
Flexbox is a layout allowing views to adjust themselves based on their content and screen size. Flexbox was originally developed for web pages, however, native implementations of the Flexbox layouting engine have been made for platforms like iOS and Android.
YogaKit
YogaKit is a Flexbox implementation for iOS. It is composed of two parts: Yoga – layouting engine, and YogaKit – iOS bindings that make Flexbox layout easy to use.
Setup
You can add YogaKit to your project using CocoaPods by adding the following line to your Podfile
: pod 'YogaKit', '~> 1.7'
and executing pod install
command.
Using YogaKit
Let’s create and configure a view that will be our root view for the Flexbox layout.
1 2 3 4 5 6 7 8 9 10 11 12 |
- (void)viewDidLayoutSubviews { UIView *flexboxRootView = [[UIView alloc] initWithFrame:CGRectZero]; flexboxRootView.backgroundColor = [UIColor yellowColor]; [flexboxRootView configureLayoutWithBlock:^(YGLayout * _Nonnull layout) { layout.isEnabled = YES; layout.flexDirection = YGFlexDirectionRow; layout.padding = YGPointValue(10); layout.width = YGPointValue(self.view.bounds.size.width); layout.height = YGPointValue(self.view.bounds.size.height); }]; [self.view addSubview:flexboxRootView]; } |
It is important to do this configuration after the root view has been layouted since we need to set width and height for the Flexbox root view. Setting dimensions is important because Flexbox won’t know about size changes of the view
.
If you are doing this in a subclass of the UIView
instead of the UIViewController
, you will have to add the code after calling the [super layoutSubviews]
in the layoutSubviews
method.
Let’s add two labels that will use Flexbox to layout.
1 2 3 4 5 6 7 8 9 10 11 12 |
for (int i=0; i<2; i++) { UILabel *view = [[UILabel alloc] initWithFrame:CGRectZero]; view.text = [NSString stringWithFormat:@"test %d", i]; view.backgroundColor = [UIColor blueColor]; [view configureLayoutWithBlock:^(YGLayout * _Nonnull layout) { layout.isEnabled = YES; layout.flexDirection = YGFlexDirectionRow; layout.padding = YGPointValue(10); }]; [flexboxRootView addSubview:view]; } [flexboxRootView.yoga applyLayoutPreservingOrigin:false]; |
This setup should generate the following result:
Conclusion
Using Flexbox in an existing project with Autolayout is possible and quite easy. For me, the most important thing was to set dimensions of a view that is meant to serve as a root view of the Flexbox layout. If you want to try something else for your layouting needs, Flexbox might be a good tool for you.
Feedback is welcome!
Want to join the discussion?Feel free to contribute!
Leave a Reply
Want to join the discussion?Feel free to contribute!