Creating a Grid Layout in iOS

As I recently mentioned over at DZone, working with auto layout in iOS has historically been somewhat difficult. Having previously built applications for other platforms with more robust layout management capabilities, I expected to find something comparable when I started doing iOS development. One of the first things I looked for was a "grid" layout that I could use to automatically arrange views in rows and columns. Such features are common on other platforms and are often used to lay out many fundamental elements of an application's user interface, from side bars and menus to feedback forms. I was disappointed to discover that nothing like this existed for iOS.

With iOS 9, Apple introduced the UIStackView class. By combining a vertical stack view with several horizontal stack views, I could much more easily create the kind of layouts I needed. And, as I mentioned in the DZone article, MarkupKit makes it even easier to work with stack views, using a declarative model similar to Android and Windows development.

For example, the following markup creates a simple form that allows a user to enter a name and address. The labels and text fields are baseline-aligned, and the entire form is hosted in a scroll view. The text fields are assigned a horizontal content hugging priority of 0 to allow them to resize:

<LMScrollView fitToWidth="true" backgroundColor="#ffffff">
    <UIStackView axis="vertical" layoutMarginsRelativeArrangement="true" layoutMargins="20" spacing="12">
        <UIStackView axis="horizontal" alignment="firstBaseline" spacing="8">
            <UILabel text="Name"/>
            <UITextField id="nameTextField" borderStyle="roundedRect"
                horizontalContentHuggingPriority="0"/>
        </UIStackView>

        <UIStackView axis="horizontal" alignment="firstBaseline" spacing="8">
            <UILabel text="Address"/>

            <UIStackView id="addressStackView" axis="vertical" spacing="8">
                <UITextField borderStyle="roundedRect" placeholder="Street"
                    horizontalContentHuggingPriority="0"/>

                <UIStackView axis="horizontal" alignment="firstBaseline" spacing="8">
                    <UITextField id="cityTextField" placeholder="City" borderStyle="roundedRect"
                        horizontalContentHuggingPriority="0"/>
                    <UITextField id="stateTextField" placeholder="State" borderStyle="roundedRect"
                        horizontalContentHuggingPriority="0"/>
                    <UITextField id="zipTextField" placeholder="Zip" borderStyle="roundedRect"
                        horizontalContentHuggingPriority="0"/>
                </UIStackView>
            </UIStackView>
        </UIStackView>
    </UIStackView>
</LMScrollView>

Unfortunately, stack views don't natively provide a way to vertically align controls, so the output of this markup doesn't look quite right:

What's worse, the text fields don't retain their original sizes once text has been entered into them:

To ensure that the controls are aligned and maintain a fixed size, the view controller needs to install some additional constraints in viewDidLoad():

import UIKit
import MarkupKit

class StackViewController: UIViewController {
    weak var nameTextField: UITextField!

    weak var addressStackView: UIStackView!

    weak var cityTextField: UITextField!
    weak var stateTextField: UITextField!
    weak var zipTextField: UITextField!

    override func loadView() {
        view = LMViewBuilder.view(withName: "StackViewController", owner: self, root: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Stack Views"

        // Create custom constraints
        NSLayoutConstraint.activate([
            // Equal-width
            NSLayoutConstraint(item: nameTextField, attribute: NSLayoutAttribute.width,
                relatedBy: NSLayoutRelation.equal, toItem: addressStackView, attribute: NSLayoutAttribute.width,
                multiplier: 1.0, constant: 0),

            // Weight
            NSLayoutConstraint(item: stateTextField, attribute: NSLayoutAttribute.width,
                relatedBy: NSLayoutRelation.equal, toItem: cityTextField, attribute: NSLayoutAttribute.width,
                multiplier: 2.0 / 3.0, constant: 0),
            NSLayoutConstraint(item: zipTextField, attribute: NSLayoutAttribute.width,
                relatedBy: NSLayoutRelation.equal, toItem: stateTextField, attribute: NSLayoutAttribute.width,
                multiplier: 2.0 / 2.0, constant: 0)
        ])
    }
}

With the additional constraints, the form behaves as expected:

However, there is an even easier way to create this layout. MarkupKit's LMColumnView and LMRowView classes can also be used to create a table-like arrangement of UI elements. Further, LMColumnView provides an alignToGrid property that can be used to ensure that nested subviews are vertically aligned, and the form fields can be weighted to ensure that they retain their relative sizes:

<LMScrollView fitToWidth="true" backgroundColor="#ffffff">
    <LMColumnView alignToGrid="true" layoutMargins="20">
        <LMRowView alignToBaseline="true">
            <UILabel text="Name"/>
            <UITextField class="textfield" borderStyle="roundedRect" weight="1"/>
        </LMRowView>

        <LMRowView alignToBaseline="true">
            <UILabel text="Address"/>

            <LMColumnView weight="1">
                <UITextField borderStyle="roundedRect" placeholder="Street"/>

                <LMRowView alignToBaseline="true">
                    <UITextField placeholder="City" borderStyle="roundedRect" weight="3"/>
                    <UITextField placeholder="State" borderStyle="roundedRect" weight="2"/>
                    <UITextField placeholder="Zip" borderStyle="roundedRect" weight="2"/>
                </LMRowView>
            </LMColumnView>
        </LMRowView>
    </LMColumnView>
</LMScrollView>

This markup produces output identical to the final stack view example, but is much less verbose, and doesn't require the use of custom constraints or content priorities:

MarkupKit's row and column views don't offer all of the features provided by UIStackView. For example, stack views provide additional alignment and distribution options as well as the ability to animate changes to their contents. However, the weight-based distribution and column alignment options supported by LMColumnView and LMRowView make them a great alternative for creating grid layouts in iOS applications.

For more information, see the MarkupKit README or the following examples:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s