Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating a Grid Layout in iOS

DZone's Guide to

Creating a Grid Layout in iOS

With iOS 9, Apple introduced the UIStackView class. By combining a vertical stack view with several horizontal stack views, I can easily create the kind of layouts I need. And, the open-source MarkupKit project makes it even easier to work with stack views, using a declarative model similar to Android and Windows development.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

As I mentioned in an earlier article, working with auto layout in iOS has historically been somewhat difficult. Having previously built applications for other platforms with more robust layout management features, 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 previous article, the open-source MarkupKit project 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 zero 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:

Image title

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

Image title

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.viewWithName("StackView", owner: self, root: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Stack View"

        // Create custom constraints
        NSLayoutConstraint.activateConstraints([
            // 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:

Image title

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:

Image title

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.

The full source code for the sample application can be found here.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
ios ,auto layout ,markupkit ,markup ,swift ,mobile

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}