Integrating Flexbox with Autolayout

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.

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.

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.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *