FlexLayout adds a nice Swift interface to the highly optimized facebook/yoga flexbox implementation. Concise, intuitive & chainable syntax.

Overview

FlexLayout

Coverage Status


FlexLayout adds a nice Swift interface to the highly optimized Yoga flexbox implementation. Concise, intuitive & chainable syntax.

Flexbox is an incredible improvement over UIStackView. It is simpler to use, much more versatile and amazingly performant.

Yoga is a multiplatform CSS Flexbox implementation (iOS/Android/...). Yoga is also the layout engine of React Native.

Requirements

  • iOS 8.0+
  • Xcode 8.0+ / Xcode 9.0+
  • Swift 3.0+ / Swift 4.0

Content


📌 FlexLayout is actively updated. So please come often to see latest changes. You can also Star it to be able to retrieve it easily later.


FlexLayout + PinLayout

FlexLayout

FlexLayout is a companion of PinLayout. They share a similar syntax and method names. PinLayout is a layout framework greatly inspired by CSS absolute positioning, it is particularly useful for greater fine control and animations. It gives you full control by layouting one view at a time (simple to code and debug).

  • A view can be layouted using FlexLayout, PinLayout, or both!
  • PinLayout can layout anything, but in situations where you need to layout many views but don't require PinLayout's finest control nor complex animations, FlexLayout is best fitted.
  • A view layouted using PinLayout can be embedded inside a FlexLayout's container and reversely. You choose the best layout framework for your situation.

FlexLayout Introduction examples

Example 1:

This example will layout multiples views using column and row flexbox containers.

Two steps to use a flexbox container:

  1. Setup the container: Initialize your flexbox structure. Note that it is also possible to alter it later.
  2. Layout the container: The layout of the container should be done from layoutSubviews() (or willTransition(to: UITraitCollection, ...) and viewWillTransition(to: CGSize, ...)).
    1. First you must layout the flexbox container, i.e. position it and optionally set its size.
    2. Then layout the flexbox children using Flex method layout().

FlexLayout example

fileprivate let rootFlexContainer = UIView()

init() {
   super.init(frame: .zero)
   
   addSubview(rootFlexContainer)
   ...

   // Column container
   rootFlexContainer.flex.direction(.column).padding(12).define { (flex) in
        // Row container
        flex.addItem().direction(.row).define { (flex) in
            flex.addItem(imageView).width(100).aspectRatio(of: imageView)
            
            // Column container
            flex.addItem().direction(.column).paddingLeft(12).grow(1).define { (flex) in
                flex.addItem(segmentedControl).marginBottom(12).grow(1)
                flex.addItem(label)
            }
        }
        
        flex.addItem().height(1).marginTop(12).backgroundColor(.lightGray)
        flex.addItem(bottomLabel).marginTop(12)
    }
}

override func layoutSubviews() {
    super.layoutSubviews() 

    // 1) Layout the flex container. This example use PinLayout for that purpose, but it could be done 
    //    also by setting the rootFlexContainer's frame:
    //       rootFlexContainer.frame = CGRect(x: 0, y: 0, 
    //                                        width: frame.width, height: rootFlexContainer.height)
    rootFlexContainer.pin.top().left().width(100%).marginTop(topLayoutGuide)

    // 2) Then let the flexbox container layout itself. Here the container's height will be adjusted automatically.
    rootFlexContainer.flex.layout(mode: .adjustHeight)
}

📌 This example is available in the Examples App. See complete source code


Example 2:

The example implements the Ray Wenderlich Yoga Tutorial screen using FlexLayout.

init() {
   ...

   rootFlexContainer.flex.define { (flex) in
        // Image
        flex.addItem(episodeImageView).grow(1).backgroundColor(.gray)
        
        // Summary row
        flex.addItem().direction(.row).padding(padding).define { (flex) in
            flex.addItem(summaryPopularityLabel).grow(1)
            
            flex.addItem().direction(.row).justifyContent(.spaceBetween).grow(2).define { (flex) in
                flex.addItem(yearLabel)
                flex.addItem(ratingLabel)
                flex.addItem(lengthLabel)
            }
            
            flex.addItem().width(100).height(1).grow(1)
        }
        
        // Title row
        flex.addItem().direction(.row).padding(padding).define { (flex) in
            flex.addItem(episodeIdLabel)
            flex.addItem(episodeTitleLabel).marginLeft(20)
        }
        
        // Description section
        flex.addItem().paddingHorizontal(paddingHorizontal).define { (flex) in
            flex.addItem(descriptionLabel)
            flex.addItem(castLabel)
            flex.addItem(creatorsLabel)
        }
        
        // Action row
        flex.addItem().direction(.row).padding(padding).define { (flex) in
            flex.addItem(addActionView)
            flex.addItem(shareActionView)
        }
        
        // Tabs row
        flex.addItem().direction(.row).padding(padding).define { (flex) in
            flex.addItem(episodesTabView)
            flex.addItem(moreTabView)
        }
        
        // Shows TableView
        flex.addItem(showsTableView).grow(1)
    }
}

override func layoutSubviews() {
    super.layoutSubviews() 

    // 1) Layout the contentView & rootFlexContainer using PinLayout
    contentView.pin.top().bottom().left().right()
    rootFlexContainer.pin.top().left().right()

    // 2) Let the flexbox container layout itself and adjust the height
    rootFlexContainer.flex.layout(mode: .adjustHeight)
    
    // 3) Adjust the scrollview contentSize
    contentView.contentSize = rootFlexContainer.frame.size
}

📌 This example is available in the Examples App. See complete source code


FlexLayout principles and philosophy

  • Flexbox layouting is simple, powerful and fast.
  • FlexLayout syntax is concise and chainable.
  • FlexLayout/yoga is incredibly fast, it's even faster than manual layout. See Performance.
  • The source code structure matches the flexbox structure, making it easier to understand and modify. Flex containers are defined on one line, and its items (children) are imbricated. This makes the flexbox structure much more visual and easy to understand.
  • Supports left-to-right (LTR) and right-to-left (RTL) languages.

NOTE: FlexLayout wraps facebook/yoga implementation and expose all its features. So note that on this documentation we will refer to FlexLayout, but this also applies to Yoga.


FlexLayout's Performance

FlexLayout's performance has been measured using the Layout Framework Benchmark. FlexLayout and PinLayout has been added to this benchmark to compare their performance.

As you can see in the following chart, FlexLayout and PinLayout's performance are faster or equal to manual layouting. FlexLayout and PinLayout are between 8x and 12x faster than UIStackViews, and this for all types of iPhone (5S/6/6S/7/8/X)

See here more complete details, results and explanation of the benchmark.


Variation from CSS flexbox

  • In many CSS methods and properties name, the keyword flex was added to control name conflicts. FlexLayout removed this keyword for being more concise and removed this unecessary keyword:

    FlexLayout Name CSS Name React Native Name
    direction flex-direction flexDirection
    wrap flex-wrap flexWrap
    grow flex-grow flexGrow
    shrink flex-shrink flexShrink
    basis flex-basis flexBasis
    start flex-start flexStart
    end flex-end flexEnd
  • FlexLayout default properties are sligthly different from CSS flexbox. This table resume these difference:

    Property FlexLayout default value CSS default value React Native default value
    direction column row column
    justifyContent start start start
    alignItems stretch stretch stretch
    alignSelf auto auto auto
    alignContent start stretch start
    grow 0 0 0
    shrink 0 1 0
    basis 0 auto 0
    wrap noWrap nowrap noWrap
  • FlexLayout additions:

    • addItem()
    • define()
    • layout()
    • isIncludedInLayout()
    • markDirty()
    • intrinsicSize
    • sizeThatFits()

NOTE: FlexLayout doesn't support the flexbox order property. The order is determined by the flex container's UIView.subviews array.


Documentation

Flexbox is pretty easy and straightforward to use. The defining aspect of the flexbox is the ability to alter its items, width, height to best fill the available space on any display device. A flex container expands its items to fill the available free space or shrinks them to prevent overflow.

The flex layout is constituted of parent container referred as flex container and its immediate children which are called flex items. A flex item can also be a flex container, i.e. it is possible to add other flex items to it.

Axes

When working with StackViews you need to think in terms of two axes — the main axis and the cross axis. The main axis is defined by StackView's direction property, and the cross axis runs perpendicular to it.

StackView direction Axes
column (default)
row
Sections

In the following sections we will see:

  1. How to create, modify and defines flex containers and items.
  2. Flexbox container's properties
  3. Flexbox item's properties

📌 This document is a guide that explains how to use FlexLayout. You can also checks the FlexLayout's API documentation.


1. Creation, modification and definition of flexbox items

addItem(:UIView)

  • Applies to: flex containers
  • Returns: FlexLayout interface of the newly added flex item.

Method:

  • addItem(_: UIView) -> Flex
    This method adds a flex item (UIView) to a flex container. Internally this method adds the UIView as a subview and enables flexbox.
Usage examples:
  view.flex.addItem(imageView).width(100).aspectRatio(1)

addItem()

  • Applies to: flex containers
  • Returns: FlexLayout interface of the newly created flex item.

Method:

  • addItem() -> Flex
    This method is similar to addItem(: UIView) except that it also creates the flex item's UIView. Internally the method creates a UIView, adds it as a subview and enables flexbox. This is useful to add a flex item/container easily when you don't need to refer to it later.
Usage examples:
  view.flex.addItem().direction(.row).padding(10)

define()

  • Applies to: flex containers
  • Parameter: Closure of type (flex: Flex) -> Void

Method:

  • define(_ closure: (_ flex: Flex) -> Void)
    This method is used to structure your code so that it matches the flexbox structure. The method has a closure parameter with a single parameter called flex. This parameter is in fact the view's flex interface. It can be used to adds other flex items and containers.
Usage examples:
  view.flex.addItem().define { (flex) in
      flex.addItem(imageView).grow(1)
		
      flex.addItem().direction(.row).define { (flex) in
          flex.addItem(titleLabel).grow(1)
          flex.addItem(priceLabel)
      }
  }

The same results can also be obtained without using the define() method, but the result is not as elegant:

  let columnContainer = UIView()
  columnContainer.flex.addItem(imageView).grow(1)
  view.flex.addItem(columnContainer)
		
  let rowContainer = UIView()
  rowContainer.flex.direction(.row)
  rowContainer.flex.addItem(titleLabel).grow(1)
  rowContainer.flex.addItem(priceLabel)
  columnContainer.flex.addItem(rowContainer)

Advantages of using define():

  • The source code structure matches the flexbox structure, making it easier to understand and modify.
    • Changing a flex item order, it's just moving up/down its line/block that defines it.
    • Moving a flex item from one container to another is just moving line/block that defines it.
  • The structure looks more similar to how HTML and React Native defines it.
  • Inside the define's closure, you can do whatever you want to fill the flexbox container. You can use for loops, iterate arrays of data, call functions, ...

Accessing flex item's UIView

It is possible to access the flex items's UIView using flex.view. This is particularly useful when using flex.define() method.

Example:

This example creates a flexbox container and sets its alpha to 0.8.

    view.flex.direction(.row).padding(20).alignItems(.center).define { (flex) in
        flex.addItem().width(50).height(50).define { (flex) in
            flex.view?.alpha = 0.8
        }
    }

Another possible solution:

    view.flex.direction(.row).padding(20).alignItems(.center).define { (flex) in
        let container = UIView()
        container.alpha = 0.8
        
        flex.addItem(container).width(50).height(50)
    }

layout()

  • Applies to: flex containers
  • Values: fitContainer / adjustWidth / adjustHeight
  • Default value: fitContainer

Method:

  • layout(mode: LayoutMode = . fitContainer)
    The method will layout the flex container's children.

    Layout modes:

    • fitContainer: This is the default mode when no parameter is specified. Children are layouted inside the container's size (width and height).
    • adjustHeight : In this mode, children are layouted using only the container's width. The container's height will be adjusted to fit the flexbox's children
    • adjustWidth : In this mode, children are layouted using only the container's height. The container's width will be adjusted to fit the flexbox's children
Usage examples:
  rootFlexContainer.flex.layout(mode: .adjustHeight)

2. Flexbox containers properties

This section describes all flex container's properties.

direction()

  • Applies to: flex containers
  • Values: column / columnReverse / row / rowReverse
  • Default value: column
  • CSS name: flex-direction

Method:

  • direction(_: Direction)
    The direction property establishes the main-axis, thus defining the direction flex items are placed in the flex container.

    The direction property specifies how flex items are laid out in the flex container, by setting the direction of the flex container’s main axis. They can be laid out in two main directions, like columns vertically or like rows horizontally.

    Note that row and row-reverse are affected by the layout direction (see layoutDirection property) of the flex container. If its text direction is LTR (left to right), row represents the horizontal axis oriented from left to right, and row-reverse from right to left; if the direction is rtl, it's the opposite.

Value Result Description
column (default) Top to bottom
columnReverse Bottom to top
row Same as text direction
rowReverse opposite to text direction
Usage examples:
  view.flex.direction(.column)  // Not required, default value. 
  view.flex.direction(.row)
Example 1:

This example center three buttons with a margin of 10 pixels between them.
Example source code

    rootFlexContainer.flex.justifyContent(.center).padding(10).define { (flex) in
        flex.addItem(button1)
        flex.addItem(button2).marginTop(10)
        flex.addItem(button3).marginTop(10)
    }

justifyContent()

  • Applies to: flex containers
  • Values: start / end / center / spaceBetween / spaceAround / spaceEvenly
  • Default value: start
  • CSS name: justify-content

Method:

  • justifyContent(_: JustifyContent)
    The justifyContent property defines the alignment along the main-axis of the current line of the flex container. It helps distribute extra free space leftover when either all the flex items on a line have reached their maximum size. For example, if children are flowing vertically, justifyContent controls how they align vertically.
direction(.column) direction(.row)
start (default) Items are packed at the beginning of the main-axis.
end Items are packed at the end of the main-axis.
center items are centered along the main-axis.
spaceBetween Items are evenly distributed in the main-axis; first item is at the beginning, last item at the end.
spaceAround Items are evenly distributed in the main-axis with equal space around them.
spaceEvenly Items are evenly distributed in the main-axis with equal space around them.
Usage examples:
  view.flex.justifyContent(.start)  // default value. 
  view.flex.justifyContent(.center)

alignItems()

  • Applies to: flex containers
  • Values: stretch / start / end / center / baseline
  • Default value: stretch
  • CSS name: align-items

Method:

  • alignItems(_: AlignItems)
    The alignItems property defines how flex items are laid out along the cross axis on the current line. Similar to justifyContent but for the cross-axis (perpendicular to the main-axis). For example, if children are flowing vertically, alignItems controls how they align horizontally.
direction(.column) direction(.row)
stretch (default)
start
end
center

alignSelf()

  • Applies to: flex containers
  • Values: auto / stretch / start / end / center / baseline
  • Default value: auto
  • CSS name: align-self

Method:

  • alignSelf(_: AlignSelf)
    The alignSelf property controls how a child aligns in the cross direction, overriding the alignItems of the parent. For example, if children are flowing vertically, alignSelf will control how the flex item will align horizontally.

The auto value means use the flex container alignItems property. See alignItems for documentation of the other values.


wrap()

  • Applies to: flex containers
  • Values: noWrap / wrap / wrapReverse
  • Default value: noWrap
  • CSS name: flex-wrap

Method:

  • wrap(_: Wrap)
    The wrap property controls whether the flex container is single-lined or multi-lined, and the direction of the cross-axis, which determines the direction in which the new lines are stacked in.

By default, the flex container fits all flex items into one line. Using this property we can change that. We can tell the container to lay out its items in single or multiple lines, and the direction the new lines are stacked in

Reminder: the cross axis is the axis perpendicular to the main axis. Its direction depends on the main axis direction.

direction(.column) direction(.row) Description
noWrap (default) Single-line which may cause the container to overflow. NEW: Flex items are displayed in one row and by default they are shrunk to fit the flex container’s width
wrap Multi-lines, direction is defined by direction(). NEW: Flex items are displayed in multiple rows if needed from left-to-right and top-to-bottom
wrapReverse Multi-lines, opposite to direction defined by direction(). NEW: Flex items are displayed in multiple rows if needed from left-to-right and bottom-to-top
Usage examples:
  view.flex.wrap(.nowrap)  // Not required, default value. 
  view.flex.wrap(.wrap)

alignContent()

  • Applies to: flex containers
  • Values: start / end / center / stretch / spaceBetween / spaceAround
  • Default value: start
  • CSS name: align-content

Method:

  • alignContent(_: AlignContent)
    The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justifyContent aligns individual items within the main-axis.

Note, alignContent has no effect when the flexbox has only a single line.

direction(.column) direction(.row)
start (default)
end
center
stretch
spaceBetween
spaceAround

layoutDirection()

FlexLayout supports left-to-right (LTR) and right-to-left (RTL) languages.

Using start or end properties, you can position views without having to think about whether your item will show up on the left or the right side of the screen (depending on the person’s language

Method:

  • layoutDirection(_: LayoutDirection)
    The layoutDirection property controls the flex container layout direction.

    Values:

    • .inherit
      Direction defaults to Inherit on all nodes except the root which defaults to LTR. It is up to you to detect the user’s preferred direction (most platforms have a standard way of doing this) and setting this direction on the root of your layout tree.
    • .ltr: Layout views from left to right. (Default)
    • .rtl: Layout views from right to left.

3. Flexbox items properties

This section describe all flex items's properties.

📌 Remembers that flex containers are also flex items, so all these properties also apply to containers.

grow

  • Applies to: flex items
  • Default value: 0
  • CSS name: flex-grow

Method:

  • grow(_: CGFloat)
    The grow property defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.

    A grow value of 0 (default value) keeps the view's size in the main-axis direction. If you want the view to use the available space set a grow value > 0.

For example, if all items have grow set to 1, every child will set to an equal size inside the container. If you were to give one of the children a value of 2, that child would take up twice as much space as the others.


shrink

  • Applies to: flex items
  • Default value: 0
  • CSS name: flex-shrink

Method:

  • shrink(_: CGFloat)
    It specifies the "flex shrink factor", which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when there isn't enough space on the main-axis.

    When omitted, it is set to 0 and the flex shrink factor is multiplied by the flex basis when distributing negative space.

    A shrink value of 0 keeps the view's size in the main-axis direction. Note that this may cause the view to overflow its flex container.

    Shrink is about proportions. If an item has a shrink of 3, and the rest have a shrink of 1, the item will shrink 3x as fast as the rest.


basis

  • Applies to: flex items
  • Default value: 0
  • CSS name: flex-basis

Method:

  • basis(_ : CGFloat?)
    This property takes the same values as the width and height properties, and specifies the initial size of the flex item, before free space is distributed according to the grow and shrink factors.

    Specifying nil set the basis as auto, which means the length is equal to the length of the item. If the item has no length specified, the length will be according to its content

  • basis(_ : FPercent)
    This property takes the same values as the width and height properties, and specifies the initial size of the flex item, before free space is distributed according to the grow and shrink factors.


isIncludedInLayout()

  • Applies to: flex items

Method:

  • isIncludedInLayout(_ value: Bool)
    This property controls dynamically if a flexbox's UIView is included or not in the flexbox layouting. When a flexbox's UIView is excluded, FlexLayout won't layout the view and its children views.

FlexLayout automatically includes the UIView when:

  • The first time UIView.flex property is accessed
  • When a child view is added to a flexbox container using addItem(:UIView) or addItem()

display

  • Applies to: flex items

Method:

  • display(_: Display)

Set the item display or not, with none value, the item will be hidden and not included in the layout.


markDirty()

  • Applies to: flex items

Method:

  • markDirty()
    The framework is so highly optimized, that flex items are layouted only when a flex property is changed and when flex container size change. In the event that you want to force FlexLayout to do a layout of a flex item, you can mark it as dirty using markDirty().

    Dirty flag propagates to the root of the flexbox tree ensuring that when any item is invalidated its whole subtree will be re-calculated.

Usage examples:

In the case where a UILabel's text is updated, it is needed to mark the label as dirty and relayout the flex container.

    // 1) Update UILabel's text
    label.text = "I love FlexLayout"
     
    // 2) Mark the UILabel as dirty
    label.flex. markDirty()
    
    // 3) Then force a relayout of the flex container.
    rootFlexContainer.flex.layout()
    OR
    setNeedsLayout()

sizeThatFits()

  • Applies to: flex items

Method:

  • sizeThatFits()
    Returns the item size when layouted in the specified frame size.
Usage Example:

Get the size of view when layouted in a container with a width of 200 pixels.

    let layoutSize = viewA.flex.sizeThatFits(CGSize(width: 200, height: CGFloat.greatestFiniteMagnitude)

intrinsicSize

  • Applies to: flex items

Property:

  • intrinsicSize
    Item natural size, considering only properties of the view itself. Independent of the item frame.

4. Absolute positioning

  • Applies to: flex items
  • Parameter: CGFloat

Method:

  • position(_: Position)
    The position property tells Flexbox how you want your item to be positioned within its parent. Position values:
    • relative (default)
    • absolute: The view is positioned using properties: top(), bottom(), left(), right(), start(), end().
Usage examples:
  view.flex.position(.absolute).top(10).left(10).size(50)

top(), bottom(), left(), right(), start(), end(), vertically(), horizontally(), all()

A flex item which is position is set to .absolute is positioned absolutely in regards to its parent. This is done through the following methods:

Methods:

  • top(: CGFloat) / top(: FPercent):
    Controls the distance a child’s top edge is from the parent’s top edge.
  • bottom(: CGFloat) / bottom(: FPercent):
    Controls the distance a child’s bottom edge is from the parent’s bottom edge.
  • left(: CGFloat) / left(: FPercent):
    Controls the distance a child’s left edge is from the parent’s left edge.
  • right(: CGFloat) / right(: FPercent):
    Controls the distance a child’s right edge is from the parent’s right edge.
  • start(: CGFloat) / start(: FPercent):
    Controls the distance a child’s start edge is from the parent’s start edge. In left-to-right direction (LTR), it corresponds to the left() property and in RTL to right() property.
  • end(: CGFloat) / end(: FPercent):
    Controls the distance a child’s end edge is from the parent’s end edge. In left-to-right direction (LTR), it corresponds to the right() property and in RTL to left() property.
  • vertically(: CGFloat) / vertically(: FPercent):
    Controls the distance child’s top and bottom edges from the parent’s edges. Equal to top().bottom().
  • horizontally(: CGFloat) / horizontally(: FPercent):
    Controls the distance child’s left and right edges from the parent’s edges. Equal to left().right().
  • all(: CGFloat) / all(: FPercent):
    Controls the distance child’s edges from the parent’s edges. Equal to top().bottom().left().right().

Using these properties you can control the size and position of an absolute item within its parent. Because absolutely positioned children don’t affect their sibling's layout. Absolute position can be used to create overlays and stack children in the Z axis.

Usage examples:
  view.flex.position(.absolute).top(10).right(10).width(100).height(50)
  view.flex.position(.absolute).left(20%).right(20%)

📌 See the "Yoga C" example in the Examples App. Source code


5. Adjusting the size

Width and height and size

FlexLayout has methods to set the view’s height and width.

Methods:

  • width(_ width: CGFloat?)
    The value specifies the view's width in pixels. The value must be non-negative. Call width(nil) to reset the property.
  • width(_ percent: FPercent)
    The value specifies the view's width in percentage of its container width. The value must be non-negative. Call width(nil) to reset the property.
  • height(_ height: CGFloat?)
    The value specifies the view's height in pixels. The value must be non-negative. Call height(nil) to reset the property.
  • height(_ percent: FPercent)
    The value specifies the view's height in percentage of its container height. The value must be non-negative. Call height(nil) to reset the property.
  • size(_ size: CGSize?)
    The value specifies view's width and the height in pixels. Values must be non-negative. Call size(nil) to reset the property.
  • size(_ sideLength: CGFloat?)
    The value specifies the width and the height of the view in pixels, creating a square view. Values must be non-negative. Call size(nil) to reset the property.
Usage examples:
  view.flex.width(100)	
  view.flex.width(50%)	
  view.flex.height(200)
	
  view.flex.size(250)

minWidth(), maxWidth(), minHeight(), maxHeight()

FlexLayout has methods to set the view’s minimum and maximum width, and minimum and maximum height.

Using minWidth, minHeight, maxWidth, and maxHeight gives you increased control over the final size of items in a layout. By mixing these properties with grow, shrink, and alignItems(.stretch), you are able to have items with dynamic size within a range which you control.

An example of when Max properties can be useful is if you are using alignItems(.stretch) but you know that your item won’t look good after it increases past a certain point. In this case, your item will stretch to the size of its parent or until it is as big as specified in the Max property.

Same goes for the Min properties when using shrink. For example, you may want children of a container to shrink to fit on one row, but if you specify a minimum width, they will break to the next line after a certain point (if you are using wrap(.wrap).

Another case where Min and Max dimension constraints are useful is when using aspectRatio.

Methods:

  • minWidth(_ width: CGFloat?)
    The value specifies the view's minimum width of the view in pixels. The value must be non-negative. Call minWidth(nil) to reset the property.
  • minWidth(_ percent: FPercent)
    The value specifies the view's minimum width of the view in percentage of its container width. The value must be non-negative. Call minWidth(nil) to reset the property..
  • maxWidth(_ width: CGFloat?)
    The value specifies the view's maximum width of the view in pixels. The value must be non-negative. Call maxWidth(nil) to reset the property.
  • maxWidth(_ percent: FPercent)
    The value specifies the view's maximum width of the view in percentage of its container width. The value must be non-negative. Call maxWidth(nil) to reset the property.
  • minHeight(_ height: CGFloat?)
    The value specifies the view's minimum height of the view in pixels. The value must be non-negative. Call minHeight(nil) to reset the property.
  • minHeight(_ percent: FPercent)
    The value specifies the view's minimum height of the view in percentage of its container height. The value must be non-negative. Call minHeight(nil) to reset the property.
  • maxHeight(_ height: CGFloat?)
    The value specifies the view's maximum height of the view in pixels. The value must be non-negative. Call maxHeight(nil) to reset the property.
  • maxHeight(_ percent: FPercent)
    The value specifies the view's maximum height of the view in percentage of its container height. The value must be non-negative. Call maxHeight(nil) to reset the property.
Usage examples:
  view.flex.maxWidth(200)
  view.flex.maxWidth(50%)
  view.flex.width(of: view1).maxWidth(250)
	
  view.flex.maxHeight(100)
  view.flex.height(of: view1).maxHeight(30%)

aspectRatio()

AspectRatio is a property introduced by Yoga that don't exist in CSS. AspectRatio solves the problem of knowing one dimension of an element and an aspect ratio, this is very common when it comes to images, videos, and other media types. AspectRatio accepts any floating point value > 0, the default is undefined.

  • AspectRatio is defined as the ratio between the width and the height of a node e.g. if a node has an aspect ratio of 2 then its width is twice the size of its height.
  • AspectRatio respects the Min and Max dimensions of an item.
  • AspectRatio has higher priority than grow.
  • If AspectRatio, Width, and Height are set then the cross dimension is overridden
  • Call aspectRatio(nil) to reset the property.
Usage examples:
  imageView.flex.aspectRatio(16/9)

6. Margins

By applying Margin to an item you specify the offset a certain edge of the item should have from it’s closest sibling or parent.

Methods:

  • marginTop(_ value: CGFloat), marginTop(_ percent: FPercent)
    Top margin specify the offset the top edge of the item should have from it’s closest sibling (item) or parent (container).
  • marginLeft(_ value: CGFloat), marginLeft(_ percent: FPercent)
    Left margin specify the offset the left edge of the item should have from it’s closest sibling (item) or parent (container).
  • marginBottom(_ value: CGFloat), marginBottom(_ percent: FPercent)
    Bottom margin specify the offset the bottom edge of the item should have from it’s closest sibling (item) or parent (container)
  • marginRight(_ value: CGFloat), marginRight(_ percent: FPercent)
    Right margin specify the offset the right edge of the item should have from it’s closest sibling (item) or parent (container).
  • marginStart(_ value: CGFloat), marginStart(_ percent: FPercent)
    Set the start margin. In LTR direction, start margin specify the left margin. In RTL direction, start margin specify the right margin.
  • marginEnd(_ value: CGFloat), marginEnd(_ percent: FPercent)
    Set the end margin. In LTR direction, end margin specify the right margin. In RTL direction, end margin specify the left margin.
  • marginHorizontal(_ value: CGFloat), marginHorizontal(_ percent: FPercent)
    Set the left, right, start and end margins to the specified value.
  • marginVertical(_ value: CGFloat), marginVertical(_ percent: FPercent)
    Set the top and bottom margins to the specified value.
  • margin(_ insets: UIEdgeInsets) Set all margins using an UIEdgeInsets. This method is particularly useful to set all margins using iOS 11 UIView.safeAreaInsets.
  • margin(_ insets: NSDirectionalEdgeInsets) Set all margins using an NSDirectionalEdgeInsets. This method is useful to set all margins using iOS 11 UIView. directionalLayoutMargins when layouting a view supporting RTL/LTR languages.
  • margin(_ value: CGFloat)
    Set all margins to the specified value.
  • margin(_ vertical: CGFloat, _ horizontal: CGFloat)
  • margin(_ top: CGFloat, _ horizontal: CGFloat, _ bottom: CGFloat)
  • margin(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat)
Usage examples:
  view.flex.margin(20)
  view.flex.marginTop(20%).marginLeft(20%)
  view.flex.marginHorizontal(20)
  view.flex.margin(safeAreaInsets)
  view.flex.margin(10, 12, 0, 12)

7. Paddings

Padding specify the offset children should have from a certain edge on the container.

Methods:

  • paddingTop(_ value: CGFloat)
  • paddingLeft(_ value: CGFloat)
  • paddingBottom(_ value: CGFloat)
  • paddingRight(_ value: CGFloat)
  • paddingStart(_ value: CGFloat)
  • paddingEnd(_ value: CGFloat)
  • paddingHorizontal(_ value: CGFloat)
  • paddingVertical(_ value: CGFloat)
  • padding(_ insets: UIEdgeInsets)
    Set all paddings using an UIEdgeInsets. This method is particularly useful to set all paddings using iOS 11 UIView.safeAreaInsets.
  • padding(_ insets: NSDirectionalEdgeInsets)
    Set all paddings using an NSDirectionalEdgeInsets. This method is particularly useful to set all padding using iOS 11 UIView. directionalLayoutMargins when layouting a view supporting RTL/LTR languages.
  • padding(_ value: CGFloat)
  • padding(_ vertical: CGFloat, _ horizontal: CGFloat)
  • padding(_ top: CGFloat, _ horizontal: CGFloat, _ bottom: CGFloat)
  • padding(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat)
Usage examples:
  view.flex.padding(20)
  view.flex.paddingBottom(20)
  view.flex.paddingHorizontal(20)
  view.flex.padding(10, 12, 0, 12)

9. Extra UIView methods

FlexLayout also adds methods to set common UIView properties.

Methods:

  • backgroundColor(_ color: UIColor)
    Set the flex item's UIView background color.
Usage examples:
  // Create a gray column container and add a black horizontal line separator 
  flex.addItem().backgroundColor(.gray).define { (flex) in
      flex.addItem().height(1).backgroundColor(.black)
  } 

FlexLayout API Documentation

The complete FlexLayout API is available here.


Example App

The FlexLayout's Example App exposes some usage example of FlexLayout.
See the Example App section to get more information.


FAQ

  • Q: The flex item overflows or is bigger than its container?
    A: By default the flex item's shrink value is 0, which keeps the item's current size in the main-axis direction. So that may cause the item to overflow its flex container. To fix that you just have to specify a shrink value bigger than 0:
   view.flex.shrink(1)
  • Q: How to keep the view size (width/height)?
    A: By default view's flex shrink value is set to 1, which reduce the size of the view if the view is bigger than its flex container in the main-axis direction. If the direction is column, the height is adjusted, if the direction is row, the width is adjusted. Setting this value to 0 will keep the view size in the main-axis direction.

  • Q: How to apply percentage from a CGFloat, a Float or an Int value?
    R: Few FlexLayout's method has a parameter of type FPercent. You can easily specify this type of parameter simply by adding the % operator to your value (eg: view.flex.width(25%). It is similar if you have a value of type CGFloat, Float or Int, simply adds the % operator:

     let percentageValue: CGFloat = 50
     view.flex.height(percentageValue%)

Flexbox interesting external links


Contributing, comments, ideas, suggestions, issues, ....

For any comments, ideas, suggestions, simply open an issue.

For issues, please have a look at Yoga's issues. Your issue may have been already reported. If not, it may be a FlexLayout issue. In this case open an issue and we'll let you know if the issue is related to Yoga's implementation.

If you find FlexLayout interesting, thanks to Star it. You'll be able to retrieve it easily later.

If you'd like to contribute, you're welcome!


Installation

CocoaPods

To integrate FlexLayout into your Xcode project using CocoaPods, specify it in your Podfile:

  pod 'FlexLayout'

Then, run pod install.

Carthage

To integrate FlexLayout into your Xcode project using Carthage:

  1. Specify in your Cartfile:
github "layoutBox/FlexLayout"
  1. Run carthage update to build frameworks.
  2. Add built FlexLayout.framework in your Xcode project in the Embedded Binaries section.

Swift Package Manager

Another Swift Package

To integrate FlexLayout into another Swift Package, add it as a dependency:

.package(url: "https://github.com/layoutBox/FlexLayout.git", from: "1.3.18")

In an Xcode target

  1. To integrate FlexLayout into an Xcode target, use the File -> Swift Packages -> Add Package Dependency menu item.
  2. Add "FLEXLAYOUT_SWIFT_PACKAGE=1" to the Xcode target's GCC_PREPROCESSOR_DEFINITIONS build setting.

Changelog

FlexLayout recent history is available in the are documented in the CHANGELOG.


License

MIT License

Comments
  • Error sending to Apple

    Error sending to Apple

    Can not fill application.

    ERROR ITMS-90087: "Unsupported Architectures. The executable for Programme.app/Frameworks/FlexLayout.framework/Frameworks/YogaKit.framework contains unsupported architectures '[x86_64, i386]'."

    ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than one bundle with the CFBundleIdentifier value 'com.facebook.YogaKit' under the iOS application 'Programme.app'."

    ERROR ITMS-90205: "Invalid Bundle. The bundle at 'Programme.app/Frameworks/FlexLayout.framework' contains disallowed nested bundles."

    ERROR ITMS-90206: "Invalid Bundle. The bundle at 'Programme.app/Frameworks/FlexLayout.framework' contains disallowed file 'Frameworks'."

    opened by sLm-s 23
  • Question marginBottom()

    Question marginBottom()

    Hi @lucdion. When we hide the object with selec.flex.isIncludedInLayout (false), it disappears, but its marginBottom (8) remains, and afterwards there is a large blank if there are many such objects. How to hide an object completely with all its indents ?

    opened by sLm-s 12
  • Cannot access flex.view in 1.3.4

    Cannot access flex.view in 1.3.4

    Per documentation:

    It is possible to access the flex items's UIView using flex.view. This is particularly useful when using flex.define() method.

    1.3.4 eliminates that by making flex.view a private method alongside fixing the retain cycle issue. This is a breaking change to the API that I don't think should be happening on a ..z version bump.

    It's really convenient to attach an extension to Flex class to do stuff like drop shadow, borders in a chainable way--it makes view descriptions very declarative. Would prefer that we don't make this var private -- developers can easily read the weak tag and understand the limitations there.

    opened by SirensOfTitan 10
  • What am I do wrong?

    What am I do wrong?

    1

    
    textView.flex.direction(.column).padding(UI.Cards.inset).justifyContent(.center).define { flex in
        
      flex.addItem(section)   
      flex.addItem().direction(.rowReverse).position(.absolute).left(UI.Cards.inset).bottom(UI.Cards.inset).right(UI.Cards.inset).justifyContent(.spaceBetween).define { flex in
        
        flex.addItem(button).height(28).maxWidth(50%).grow(1).position(.absolute).right(0).bottom(0)
        flex.addItem().direction(.column).define {
    
           flex.addItem(title).shrink(1)
           flex.addItem(subtitle).shrink(1)
        }
      }
    }
    
    question 
    opened by dillidon 9
  • Nice work! May I ask some questions?

    Nice work! May I ask some questions?

    I read about YogaKit and your FlexLayout recently and I found that there is rarely a detail example or a guide to use it in normal development. I'm interesting in Yoga and FlexLayout and I consider two questions if I choose to import it in my project:

    1. How does YogaKit or FlexLayout calculate cell heights in tableview or collectionview?
    2. How to use YogaKit or FlexLayout to do animations?
    question 
    opened by wjling 9
  • Can not use FlexLayout into SwiftPM as a dependency.

    Can not use FlexLayout into SwiftPM as a dependency.

    Xcode given an error: could not found 'YGEnums.h'

    I think, the swiftpm's define (cSettings, cxxSettings, swiftSettings) can not be use in swiftpm build or archive. (Probably just a temporary bug.)

    I'm trying to use SWIFT_PACKAGE instead FLEXLAYOUT_SWIFT_PACKAGE, can be added to swiftpm as a dependency or as a standalone swiftpm.

    opened by iWECon 7
  • Writing custom views for use in flex layouts

    Writing custom views for use in flex layouts

    Hello,

    I've been exploring the use of this library and something that isn't quite clear to me is how to properly set up custom UIView subclasses for use in larger parent flex layouts – primarily, what properties/methods one should override in order for the parent layout to properly size and place these views.

    I've sifted through the examples and docs and haven't found anything that elaborates on this subject, with the focus seemingly mostly being on using UIKit-provided primitives (UILabel, UIButton, etc) in layouts. Have I missed anything?

    Thanks!

    question 
    opened by jwells89 7
  • Update license to MIT

    Update license to MIT

    Following the recent update of Yoga license to MIT shouldn't FlexLayout update the license of FlexLayout and PinLayout to MIT also. It will be very much appreciated.

    question 
    opened by tsafrir 7
  • Need some help about layout wrap

    Need some help about layout wrap

    I'm new to use FlexLayout, and I want to layout 2~9 imageViews (aspectRatio 1:1) like this: image

    But I try my best, not really exact: image

    My code is here, hope you can give me some solution😆 :

    import UIKit
    import FlexLayout
    import PinLayout
    
    class TestView: UIView {
        fileprivate let rootFlexContainer = UIView()
        
        init() {
            super.init(frame: .zero)
            backgroundColor = .white
            rootFlexContainer.backgroundColor = .yellow
            addSubview(rootFlexContainer)
            
            var picViews = [UIImageView]()
            for _ in 0..<9 {
                let imageView = UIImageView(image: UIImage(named: "method"))
                imageView.contentMode = .scaleAspectFill
                imageView.clipsToBounds = true
                picViews.append(imageView)
                rootFlexContainer.addSubview(imageView)
            }
            
            rootFlexContainer.flex.direction(.row).wrap(.wrap)
                .marginLeft(50).marginTop(100).define { flex in
                for (i, imgV) in picViews.enumerated() {
                    flex.addItem(imgV).width(30%).aspectRatio(1)
                    if i % 3 > 0 { // 右2列
                        imgV.flex.marginLeft(10)
                    }
                    if i / 3 > 0 { // 下2行
                        imgV.flex.marginTop(10)
                    }
                }
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            rootFlexContainer.pin.top().horizontally().width(87%)
            rootFlexContainer.flex.layout(mode: .adjustHeight)
        }
    }
    
    question 
    opened by darkhandz 7
  • Can a constraint be removed?

    Can a constraint be removed?

    Hello. I want to ask a question. I have an UIImageView as this:

    imageView.flex.size(someSize)
    

    If I don't want the size constraint in some conditions and use imageView's intrinsic size, how can I remove the size constraints to the imageView?

    enhancement 
    opened by wjling 7
  • Adds Swift Package Manager Support

    Adds Swift Package Manager Support

    Resolves #144

    • Isolates all the C & Non-C code
    • Adds a swift package manifest with targets for FlexLayout, FlexLayoutYoga, and FlexLayoutYogaKit
    • Moves the public headers to the [target]/include/[target] folder per Apple's documentation
    • Adds a new target to the FlexLayoutSample project called FlexLayoutExampleSPM that imports FlexLayout via the Swift package.

    NS_ENUM typedefs don't seem to be translated to Swift enums when imported via a module. Because of that, static values were added to the various NS_ENUM types as extensions when in the context of a Swift package. Perhaps there's a build setting to eliminate the need for that?

    CAVEAT

    To build a target that imports FlexLayout via the new swift package, you'll need to add FLEXLAYOUT_SWIFT_PACKAGE=1 to the target's GCC_PREPROCESSOR_DEFINITIONS build setting. The new FlexLayoutExampleSPM target does this, so look there for an example.

    The reason is that there appears to be an Xcode/SwiftPM/Both bug regarding the SWIFT_PACKAGE macro. As a result, when building an application target that includes FlexLayout via the new Swift package, the SWIFT_PACKAGE macro is undefined when compiling the FlexLayoutYogaKit target, which causes the build to fail. To work around this, I defined a new macro in the swift package called FLEXLAYOUT_SWIFT_PACKAGE and replaced all usages of SWIFT_PACKAGE with FLEXLAYOUT_SWIFT_PACKAGE. This way, you can safely define the macro in your own targets and allow the build to succeed.

    opened by gcox 6
  • Pods/FlexLayout/Sources/yoga/Yoga-internal.h:9:10: 'algorithm' file not found

    Pods/FlexLayout/Sources/yoga/Yoga-internal.h:9:10: 'algorithm' file not found

    My Podfile use #use_frameworks! add :modular_headers => true in tail Pod 'Flexlayout' after pod install. Pods/FlexLayout/Sources/yoga/Yoga-internal.h:9:10: error: 'algorithm' file not found #include ^ :0: error: could not build Objective-C module 'FlexLayout'

    Xcode: Version 13.4.1 (13F100) MacOS: 12.4 M1

    opened by dushandz 1
  • Why is the subview constraint incorrect?

    Why is the subview constraint incorrect?

    Thanks for creating a really nice library, but I'm a little confused right now. Constraints not working after using FlexLayout for subviews

    class CellsViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad() view.flex.define { flex in flex.addItem(infoView).height(60).marginTop(64) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.flex.layout() } lazy var infoView: AnimationView = { let value = AnimationView(frame: .zero) return value }()

    }

    class AnimationView: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .green flex.paddingHorizontal(12) .alignItems(.center) .direction(.row) .define { flex in flex.addItem(doubleTitileView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var doubleTitileView: DoubleTitleView = { let value = DoubleTitleView(frame: .zero) return value }() override func layoutSubviews() { super.layoutSubviews() self.layout() } func layout(){ self.flex.layout() } }

    class DoubleTitleView: UIView { override init(frame: CGRect) { super.init(frame: frame) initInterface() }

    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initInterface() { self.flex.direction(.column) .justifyContent(.center) .define { flex in flex.addItem(titleLabel) flex.addItem(subLabel) } } override func layoutSubviews() { super.layoutSubviews() self.flex.layout() } lazy var titleLabel: UILabel = { let value = UILabel() value.font = UIFont.systemFont(ofSize: 16) value.text = "textOne" return value }() lazy var subLabel: UILabel = { let value = UILabel() value.font = UIFont.systemFont(ofSize: 14) value.text = "textOneTwo" return value }() }

    image

    The padding and alignItems doesn`t work

    opened by shmilyQin 0
  • The line pixel error

    The line pixel error

    We try to make an application with the FlexLayout. The error occurs from the gap between Yoga library calculated value and the actual value for a UIView.

    In a case...

    In Yoga.cpp, func YGNodelayoutImpl() { ... } else if (alignItem == YGAlignCenter) { //leadingCrossDim += round(remainingCrossDim / 2); //Try to fix leadingCrossDim += remainingCrossDim / 2; } else { ... }

    the remainingCrossDim is 37.5 remainingCrossDim / 2 is "18.75"

    In YGLayout.mm func YGApplyLayoutToViewHierarchy() { ...

    const CGPoint origin = preserveOrigin ? view.frame.origin : CGPointZero; view.frame = (CGRect) { .origin = { .x = YGRoundPixelValue(topLeft.x + origin.x), .y = YGRoundPixelValue(topLeft.y + origin.y), }, .size = { .width = YGRoundPixelValue(bottomRight.x) - YGRoundPixelValue(topLeft.x), .height = YGRoundPixelValue(bottomRight.y) - YGRoundPixelValue(topLeft.y), }, }; ... }

    the topLeft.x returns "19"

    The gap (between 18.75 and 19 = 0.25) makes the application view hidden in a case.

    if we put the source below, the problem is solved. leadingCrossDim += round(remainingCrossDim / 2); //Try to fix

    please check and confirm this.

    스크린샷 2021-07-22 오전 9 04 03 스크린샷 2021-07-23 오전 8 56 01
    opened by hayounghoon 0
  • Is it possible to use a custom UIView constructed using autolayout to be used inside flex layout?

    Is it possible to use a custom UIView constructed using autolayout to be used inside flex layout?

    I have a complicated UIView with a lot of children laid out using autolayout. Can this be used inside flex layout with minimum effort? Right now constraints break and the view is not laid out properly.

    Simplified POC - https://github.com/rakeshashastri/flexLayoutPOC/commit/3ed6f2f7bc48986ede5507be6427ebb904a5b0c3

    opened by rakeshashastri 1
Releases(1.3.25)
  • 1.3.25(Dec 23, 2022)

  • 1.3.24(Apr 8, 2022)

  • 1.3.23(Nov 22, 2021)

    Percent padding support.

    New methods:

    • paddingTop(_ percent: FPercent)**
    • paddingLeft(_ percent: FPercent)**
    • paddingBottom(_ percent: FPercent)**
    • paddingRight(_ percent: FPercent)**
    • paddingStart(_ percent: FPercent)**
    • paddingEnd(_ percent: FPercent)**
    • paddingHorizontal(_ percent: FPercent)**
    • paddingVertical(_ percent: FPercent)**

    Added by albertocs-noma in Pull Request #159

    Source code(tar.gz)
    Source code(zip)
  • 1.3.21(May 21, 2021)

  • 1.3.20(May 29, 2020)

  • 1.3.18(May 1, 2020)

  • 1.3.17(Oct 9, 2019)

    Add new methods to position items in absolute positionning (https://github.com/layoutBox/FlexLayout#4-absolute-positioning):

    • vertically(: CGFloat) / vertically(: FPercent):
      Controls the distance child’s top and bottom edges from the parent’s edges. Equal to top().bottom().
    • horizontally(: CGFloat) / horizontally(: FPercent):
      Controls the distance child’s left and right edges from the parent’s edges. Equal to left().right().
    • all(: CGFloat) / all(: FPercent):
      Controls the distance child’s edges from the parent’s edges. Equal to top().bottom().left().right().

    Added by Kuluum in Pull Request #146

    Source code(tar.gz)
    Source code(zip)
  • 1.3.16(Aug 3, 2019)

    1.3.16

    Released on 2019-08-03

    • Delegate isIncludedInLayout to yoga vs using default value:
      Previously the value of isIncludedInLayout may have not reflect what the underlying yoga value is as the developer may have manipulated the yoga value directly. This could potentially leave the Flex initial value out of sync. This change defers the get/set of this property to yoga.
    Source code(tar.gz)
    Source code(zip)
  • 1.3.15(Jun 8, 2019)

  • 1.3.14(May 17, 2019)

  • 1.3.12(Feb 6, 2019)

  • 1.3.11(Aug 9, 2018)

  • 1.3.10(Jul 24, 2018)

  • 1.3.9(May 31, 2018)

  • 1.3.8(May 10, 2018)

  • 1.3.7(May 2, 2018)

  • 1.3.6(Apr 16, 2018)

  • 1.3.5(Mar 6, 2018)

  • 1.3.4(Mar 5, 2018)

  • 1.3.3(Feb 28, 2018)

    Fix Yoga's rounding issues

    • Integer truncation of sizes calculated by sizeThatFits:, and utility functions. Introduced by Obj-C -> Obj-C++ conversion in previous PR
    • Low coordinate rounding threshold, which results in flooring apparently valid values. Layout becomes very wrong with absolute coordinate values larger than 100 and having pointScaleFactor set to 3.
    • Added by Alexey Zinchenko in Pull Request #63
    Source code(tar.gz)
    Source code(zip)
  • 1.3.2(Feb 27, 2018)

    Update Yoga core to latest master

    • Yoga core updated to facebook/yoga@295d111 (v 1.7)
    • Yoga core tests and their buck configuration added, see core-tests folder
    • Add buck tests to CI config
    • Added by Alexey Zinchenko in Pull Request #62
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Feb 23, 2018)

    That was not my first choice, but Yoga's repository is diverging from our iOS needs.

    Reasons:

    • Yoga is now C++ and not C anymore. This was causing issues when built into frameworks.

    • FlexLayout Carthage support was not really great using Yoga's repository. The previous solution was already using a fork of Yoga's repo, but there was some issues while deploying app to the App store (embedding frameworks).

    Source code(tar.gz)
    Source code(zip)
  • 1.2.2(Dec 21, 2017)

    Add margins methods taking percentage parameters:

    • marginTop(_ percent: FPercent)
      Top margin specify the offset the top edge of the item should have from it’s closest sibling (item) or parent (container).
    • marginLeft(_ percent: FPercent)
      Left margin specify the offset the left edge of the item should have from it’s closest sibling (item) or parent (container).
    • marginBottom(_ percent: FPercent)
      Bottom margin specify the offset the bottom edge of the item should have from it’s closest sibling (item) or parent (container)
    • marginRight(_ percent: FPercent)
      Right margin specify the offset the right edge of the item should have from it’s closest sibling (item) or parent (container).
    • marginStart(_ percent: FPercent)
      Set the start margin. In LTR direction, start margin specify the left margin. In RTL direction, start margin specify the right margin.
    • marginEnd(_ percent: FPercent)
      Set the end margin. In LTR direction, end margin specify the right margin. In RTL direction, end margin specify the left margin.
    • marginHorizontal(_ percent: FPercent)
      Set the left, right, start and end margins to the specified value.
    • marginVertical(_ percent: FPercent)
      Set the top and bottom margins to the specified value.
    Usage examples:
      view.flex.margin(20%)
      view.flex.marginTop(20%).marginLeft(20%)
      view.flex.marginHorizontal(10%)
    
    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Nov 28, 2017)

    • Many properties can be reset to their initial state. Specifying nil when calling these properties reset their value:

      • width(nil)
      • height(nil)
      • size(nil)
      • minWidth(nil)
      • maxWidth(nil)
      • minHeight(nil)
      • maxHeight(nil)
      • aspectRatio(nil)
    • FlexLayout now integrates YogaKit source code, this was needed to improve efficiently the iOS's yoga interface.

    • Added by Luc Dion in Pull Request #40

    Source code(tar.gz)
    Source code(zip)
  • 1.1.8(Nov 23, 2017)

  • 1.1.5(Oct 31, 2017)

    • Add new margin methods:

      • margin(_ insets: UIEdgeInsets): Set all margins using UIEdgeInsets. This method is particularly useful to set all margins using iOS 11 UIView.safeAreaInsets
      • margin(_ directionalInsets: NSDirectionalEdgeInsets): Set margins using NSDirectionalEdgeInsets. This method is particularly to set all margins using iOS 11 UIView.directionalLayoutMargins
    • Add new padding methods:

      • padding(_ insets: UIEdgeInsets): Set all paddings using UIEdgeInsets. This method is particularly useful using iOS 11 UIView.safeAreaInsets
      • padding(_ directionalInsets: NSDirectionalEdgeInsets): Set paddings using NSDirectionalEdgeInsets. This method is particularly useful to set all paddings using iOS 11 UIView.directionalLayoutMargins
    • Update all examples to support iPhone X landscape orientation.

    • Add an example of UICollectionView using FlexLayout

    Source code(tar.gz)
    Source code(zip)
  • 1.1.4(Oct 18, 2017)

    Add width/height methods taking percentage parameter * width(_ percent: FPercent) * height(_ percent: FPercent) * minWidth(_ percent: FPercent) * maxWidth(_ percent: FPercent) * minHeight(_ percent: FPercent) * maxHeight(_ percent: FPercent)

    Usage examples:
    
    * view.flex.width(50%)
    * view.flex.height(25%)
    
    * Added by [Luc Dion](https://github.com/lucdion) in Pull Request [#28](https://github.com/lucdion/FlexLayout/pull/28) 
    
    Source code(tar.gz)
    Source code(zip)
  • 1.1.3(Oct 2, 2017)

  • 1.1.1(Aug 25, 2017)

    Replace the unique Align enumeration by 3 enumerations:

    • AlignContent
    • AlignItems
    • AlignSelf

    They all have different options, which make the API cleaner.

    Plus:

    • Removed the overflow() method for now.
    Source code(tar.gz)
    Source code(zip)
Owner
layoutBox
Set of Swift layout related projects
layoutBox
An flexbox layout aimed at easy to use, which depend on Yoga.

DDFlexbox A flexbox framework for easy using. Install pod 'DDFlexbox' Template install Recommend using templates to create flexbox views. cd Script/

Daniel 12 Mar 23, 2022
Yoga is a cross-platform layout engine which implements Flexbox.

Yoga Building Yoga builds with buck. Make sure you install buck before contributing to Yoga. Yoga's main implementation is in C++, with bindings to su

Meta 15.8k Jan 9, 2023
Flexbox in Swift, using Facebook's css-layout.

SwiftBox A Swift wrapper around Facebook's implementation of CSS's flexbox. Example let parent = Node(size: CGSize(width: 300, height: 300),

Josh Abernathy 811 Jun 23, 2022
Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout

Masonry Masonry is still actively maintained, we are committed to fixing bugs and merging good quality PRs from the wider community. However if you're

null 18k Jan 5, 2023
MisterFusion is Swift DSL for AutoLayout. It is the extremely clear, but concise syntax, in addition, can be used in both Swift and Objective-C. Support Safe Area and Size Class.

MisterFusion MisterFusion makes more easier to use AutoLayout in Swift & Objective-C code. Features Simple And Concise Syntax Use in Swift and Objecti

Taiki Suzuki 316 Nov 17, 2022
Declarative iOS UI sugar framework built on FlexLayout

Declarative iOS UI sugar framework built on FlexLayout

당근마켓 97 Dec 9, 2022
Elegant library that wraps working with frames with a nice chaining syntax.

Everyone wants to see smooth scrolling, that tableview or collectionview scrolls without any lags and it's right choice. But the constraints do not gi

Nikita Ermolenko 133 Oct 9, 2022
Zelda 是一个支持链式语法的 FlexBox 布局库,是针对 YogaKit 的二次封装

Zelda 是一个支持链式语法的 FlexBox 布局库,是针对 YogaKit 的二次封装,可以快速的让 iOS 原生开发人员使用 FlexBox 技术进行 UI 布局。

饼 4 Aug 24, 2021
Intuitive and powerful Auto Layout library

Align introduces a better alternative to Auto Layout anchors. Semantic. Align APIs focus on your goals, not the math behind Auto Layout constraints. P

Alexander Grebenyuk 338 Oct 18, 2022
Write concise Autolayout code

Winner of Hacking with Swift Recommended award You + Stevia = ?? ?? Write concise, readable layouts ?? Reduce your maintenance time ?? Compose your st

Fresh 3.3k Jan 6, 2023
Concise Auto Layout API to chain programmatic constraints while easily updating existing constraints.

Concise API for Auto Layout. SnapLayout extends UIView and NSView to deliver a list of APIs to improve readability while also shortening constraint co

Satinder Singh 11 Dec 17, 2021
UIView extension that adds dragging capabilities

YiViewDrag Installation YiViewDrag is available through CocoaPods. To install it, simply add the following line to your Podfile: pod 'YiViewDrag' Usag

coderyi 1 Jan 20, 2022
A SwiftUI proof-of-concept, and some sleight-of-hand, which adds rain to a view's background

Atmos A SwiftUI proof-of-concept, and some sleight-of-hand, which adds rain to a view's background. "Ima use this in my app..." Introducing Metal to S

Nate de Jager 208 Jan 2, 2023
This is a simple chat application made in Swift using send and receive interface.

Flash Chat ????‍♂️ Overview This is a simple chat application made in Swift using send and receive interface. ⚙️ How it works The user needs to first

Sougato Roy 2 Aug 4, 2022
Arrange views in your app’s interface using layout tools that SwiftUI provides.

Composing custom layouts with SwiftUI Arrange views in your app's interface using layout tools that SwiftUI provides. Overview This sample app demonst

Apple Sample Code 0 Jun 9, 2022
Fancy Swift implementation of the Visual Format Language (experimental and doesn't work with the recent version of Swift)

VFLToolbox Autolayout is awesome! VFL a.k.a Visual Format Language is even more awesome because it allows you to shorten constraints setting code. The

0xc010d 144 Jun 29, 2022
sample project for `UICollectionViewLayout` implementation

collection-view-layout-pattern-sample UICollectionViewLayout implementation pattern. About This project is introduced in iOSDC Japan 2021. sample code

Toshiki Takezawa 13 Nov 3, 2021
VerticalFlowLayout - This implementation is built using a UICollectionView and a custom flowLayout.

VerticalFlowLayout This implementation is built using a UICollectionView and a custom flowLayout. Table of contents Requirements Installation CocoaPod

Alexander Sibirtsev 2 Apr 19, 2022
ios-queryable is an implementation of IQueryable/IEnumerable for Core Data

#ios-queryable is an Objective-C category that provides IQueryable and IEnumerable-like functionality to Core Data. Tired of writing boilerplate Core

Marty Dill 227 Mar 3, 2022