Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

layoutBox/FlexLayout

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FlexLayout


FlexLayout adds a nice Swift interface to the highly optimizedYoga 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 12.0+
  • Xcode 12.0+
  • Swift Swift 4.0

Content


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


FlexLayout + PinLayout

FlexLayout

FlexLayout is a companion ofPinLayout. 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 fromlayoutSubviews() (orwillTransition(to: UITraitCollection, ...) andviewWillTransition(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 methodlayout().

FlexLayout example

fileprivateletrootFlexContainer=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)}}overridefunc 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 theExamples App. See completesource code


Example 2:

The example implements theRay 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)}}overridefunc 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 theExamples App. See completesource 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. SeePerformance.
  • 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 wrapsfacebook/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 theLayout Framework Benchmark. FlexLayout andPinLayout 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 arebetween 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 keywordflex was added to control name conflicts. FlexLayout removed this keyword for being more concise and removed this unecessary keyword:

    FlexLayout NameCSS NameReact Native Name
    directionflex-directionflexDirection
    wrapflex-wrapflexWrap
    growflex-growflexGrow
    shrinkflex-shrinkflexShrink
    basisflex-basisflexBasis
    startflex-startflexStart
    endflex-endflexEnd
  • FlexLayout default properties are sligthly different from CSS flexbox. This table resume these difference:

    PropertyFlexLayout default valueCSS default valueReact Native default value
    directioncolumnrowcolumn
    justifyContentstartstartstart
    alignItemsstretchstretchstretch
    alignSelfautoautoauto
    alignContentstartstretchstart
    grow000
    shrink010
    basis0auto0
    wrapnoWrapnowrapnoWrap
  • FlexLayout additions:

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

NOTE:FlexLayout doesn't support the flexboxorder property. The order is determined by the flex container'sUIView.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 asflex container and its immediate children which are calledflex 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'sdirection property, and the cross axis runs perpendicular to it.

StackView directionAxes
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 theFlexLayout'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 toaddItem(: 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 calledflex. 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 thedefine() method, but the result is not as elegant:

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

Advantages of usingdefine():

  • 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 thedefine's closure, you can do whatever you want to fill the flexbox container. You can usefor loops, iterate arrays of data, call functions, ...

Accessing flex item's UIView

It is possible to access the flex items's UIView usingflex.view. This is particularly useful when usingflex.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)inletcontainer=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 layoutedinside the container's size (width and height).
    • adjustHeight: In this mode, children are layoutedusing only the container's width. The container's height will be adjusted to fit the flexbox's children
    • adjustWidth: In this mode, children are layoutedusing 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

Property:

  • direction: Direction?

Method:

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

    Thedirection 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 (seelayoutDirection 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.

ValueResultDescription
column (default)Top to bottom
columnReverseBottom to top
rowSame as text direction
rowReverseopposite 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)
    ThejustifyContent 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.
endItems are packed at the end of the main-axis.
centeritems are centered along the main-axis.
spaceBetweenItems are evenly distributed in the main-axis; first item is at the beginning, last item at the end.
spaceAroundItems are evenly distributed in the main-axis with equal space around them.
spaceEvenlyItems 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)
    ThealignItems property defines how flex items are laid out along the cross axis on the current line. Similar tojustifyContent 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)
    ThealignSelf property controls how a child aligns in the cross direction, overriding thealignItems of the parent. For example, if children are flowing vertically,alignSelf will control how the flex item will align horizontally.

Theauto value means use the flex containeralignItems property. SeealignItems 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)
    Thewrap 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
wrapMulti-lines, direction is defined bydirection(). NEW: Flex items are displayed in multiple rows if needed from left-to-right and top-to-bottom
wrapReverseMulti-lines, opposite to direction defined bydirection(). 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 /spaceEvenly
  • 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
spaceEvenly

layoutDirection()

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

Usingstart orend 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)
    ThelayoutDirection 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)
    Thegrow 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 havegrow 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 flexbasis 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.

    Specifyingnil set the basis asauto, 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.


gap

  • Applies to:flex containers
  • CSS name:gap

Method:

  • columnGap(_ value: CGFloat)This property set distance between columns.

  • rowGap(_ value: CGFloat)This property set distance between rows.

  • gap(_ value: CGFloat)This property set distance between both of rows and columns.


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 timeUIView.flex property is accessed
  • When a child view is added to a flexbox container usingaddItem(:UIView) oraddItem()

display

  • Applies to:flex items

Method:

  • display(_: Display)

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

Values:

  • flex: Default value. The item is displayed normally and included in the layout.
  • none: The item will be hidden and not included in the layout.
  • contents: The node is removed from the layout flow, while its children are preserved and hoisted. This allows higher-level UI frameworks to compose wrapper components (e.g., to handle events) without influencing the layout of child nodes.

boxSizing

  • Applies to:flex items

Method:

  • boxSizing(_: BoxSizing)

Set the box sizing mode for the item. This determines how the width and height of an element are calculated.

Values:

  • borderBox: Default value. WithborderBox, the specified dimensions (width, height) include the content, padding, and border. This means the overall size of the element is as defined, with padding and border accounted for inside.
  • contentBox: WithcontentBox, the specified dimensions refer only to the content area. Padding and borders are added outside these dimensions, potentially increasing the total size of the element.

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 usingmarkDirty().

    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()    ORsetNeedsLayout()

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.

letlayoutSize= viewA.flex.sizeThatFits(size: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. 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) The view is positioned using Insets properties (top, bottom, left, right, start, end) from its normal position within its flex container and will take up space within the flex container. This node will always form a containing block.
    • absolute: The view is removed from the flex container's flow and is positioned using Insets properties (top, bottom, left, right, start, end). Insets will offset the node from its containing block.
    • static: The view ignores insets and will not form a containing block.
Usage examples:
  view.flex.position(.relative).top(10).left(10).size(50)  view.flex.position(.absolute).top(10).left(10).size(50)

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

A flex item with position set to .relative is positioned relative to its normal position within its flex container. Only one property can be applied in each direction, either vertical or horizontal. If bothtop andbottom properties are set,top takes precedence. If bothleft andright properties are set,left takes precedence.

A flex item with position set to .absolute is positioned absolutely with respect to its containing block. 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.

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 theleft() property and in RTL toright() 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 theright() property and in RTL toleft() property.
  • vertically(: CGFloat) /vertically(: FPercent):
    Controls the distance child’s top and bottom edges from the parent’s edges. Equal totop().bottom().
  • horizontally(: CGFloat) /horizontally(: FPercent):
    Controls the distance child’s left and right edges from the parent’s edges. Equal toleft().right().
  • all(: CGFloat) /all(: FPercent):
    Controls the distance child’s edges from the parent’s edges. Equal totop().bottom().left().right().
Usage examples:
  view.flex.position(.relative).top(10).right(10).width(100).height(50)  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 theExamples 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. Callwidth(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. Callwidth(nil) to reset the property.
  • height(_ height: CGFloat?)
    The value specifies the view's height in pixels. The value must be non-negative. Callheight(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. Callheight(nil) to reset the property.
  • size(_ size: CGSize?)
    The value specifies view's width and the height in pixels. Values must be non-negative. Callsize(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. Callsize(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 withgrow,shrink, andalignItems(.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 usingalignItems(.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 usingshrink. 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 usingwrap(.wrap).

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

Methods:

  • minWidth(_ width: CGFloat?)
    The value specifies the view's minimum width of the view in pixels. The value must be non-negative. CallminWidth(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. CallminWidth(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. CallmaxWidth(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. CallmaxWidth(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. CallminHeight(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. CallminHeight(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. CallmaxHeight(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. CallmaxHeight(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 thangrow.
  • If AspectRatio, Width, and Height are set then the cross dimension is overridden
  • CallaspectRatio(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 theleft margin. In RTL direction, start margin specify theright margin.
  • marginEnd(_ value: CGFloat),marginEnd(_ percent: FPercent)
    Set the end margin. In LTR direction, end margin specify theright margin. In RTL direction, end margin specify theleft 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 11UIView.safeAreaInsets.
  • margin(_ insets: NSDirectionalEdgeInsets)Set all margins using an NSDirectionalEdgeInsets. This method is useful to set all margins using iOS 11UIView. 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 theoffset children should have from a certain edge on the container.

Methods:

  • paddingTop(_ value: CGFloat),paddingTop(_ percent: FPercent)
  • paddingLeft(_ value: CGFloat),paddingLeft(_ percent: FPercent)
  • paddingBottom(_ value: CGFloat),paddingBottom(_ percent: FPercent)
  • paddingRight(_ value: CGFloat),paddingRight(_ percent: FPercent)
  • paddingStart(_ value: CGFloat),paddingStart(_ percent: FPercent)
  • paddingEnd(_ value: CGFloat),paddingEnd(_ percent: FPercent)
  • paddingHorizontal(_ value: CGFloat),paddingHorizontal(_ percent: FPercent)
  • paddingVertical(_ value: CGFloat),paddingVertical(_ percent: FPercent)
  • padding(_ insets: UIEdgeInsets)Set all paddings using an UIEdgeInsets. This method is particularly useful to set all paddings using iOS 11UIView.safeAreaInsets.
  • padding(_ insets: NSDirectionalEdgeInsets)
    Set all paddings using an NSDirectionalEdgeInsets. This method is particularly useful to set all padding using iOS 11UIView. directionalLayoutMargins when layouting a view supporting RTL/LTR languages.
  • padding(_ value: CGFloat),padding(_ percent: FPercent)
  • padding(_ vertical: CGFloat, _ horizontal: CGFloat),padding(_ vertical: FPercent, horizontal: FPercent
  • padding(_ top: CGFloat, _ horizontal: CGFloat, _ bottom: CGFloat),padding(_ top: FPercent, _ horizontal: FPercent, _ bottom: FPercent)
  • padding(_ top: CGFloat, _ left: FPercent, _ bottom: FPercent, _ right: FPercent),padding(_ top: FPercent, _ left: FPercent, _ bottom: FPercent, _ right: FPercent)
Usage examples:
  view.flex.padding(20)  view.flex.paddingTop(20%).paddingLeft(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.
  • cornerRadius(_ value: CGFloat)
    Set the flex item's UIView rounded corner radius.
  • border(_ width: CGFloat, _ color: UIColor)
    Set the flex item's UIView border.
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)}  // Set rounded corner  flex.addItem().cornerRadius(12)  // Set border  flex.addItem().border(1,.black)

FlexLayout API Documentation

Thecomplete 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'sshrink 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 ashrink 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 typeFPercent. 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:

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

Flexbox interesting external links


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

For anycomments,ideas,suggestions, simply open anissue.

Forissues, please have a look atYoga'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 toStar 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 yourPodfile:

pod'FlexLayout'

Then, runpod install.

Carthage

To integrate FlexLayout into your Xcode project using Carthage:

  1. Specify in yourCartfile:
github "layoutBox/FlexLayout"
  1. Runcarthage update to build frameworks.
  2. Add builtFlexLayout.framework in your Xcode project in theEmbedded 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

To integrate FlexLayout into an Xcode target, use theFile -> Swift Packages -> Add Package Dependency menu item.


Changelog

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


License

MIT License


[8]ページ先頭

©2009-2025 Movatter.jp