Skip to content

Tables and Grids Guide

Matt Greenfield edited this page Aug 15, 2014 · 12 revisions

MGBoxKit provides layout engines for tables and grids and two content providing APIs, one suitable for small tables and one suitable for large. The small table API is quick and easy to use and most suitable for static tables or dynamic tables with small data sets. For larger data sets it's most appropriate to use the dynamic API which supports box reuse and offscreen culling.

Basics

All tables and grids require an MGBox or MGScrollView container and MGLayoutBox content items (eg MGBox, MGLine. Think of it as similar to creating a UIScrollView and adding subviews, with the main difference being that you add the content items to boxes instead of to subviews.

Scrollable Container

MGScrollView *scroller = [MGScrollView scrollerWithSize:self.view.size];
[self.view addSubview:scroller];

Not Scrollable Container

MGBox *container = [MGBox boxWithSize:self.view.size];
[self.view addSubview:container];

Small/Static Table API

For small static tables and grids the easiest approach is to create and add box objects to a container's boxes array, then call the container's layout or layoutWithDuration:completion: method.

Add A Header Row

MGLine *header = [MGLine lineWithSize:(CGSize){320, 40}];
header.bottomBorderColor = UIColor.lightGrayColor;
header.padding = UIEdgeInsetsMake(0, 16, 0, 16);
header.leftItems = (id)@"This is a Heading";
[scroller.boxes addObject:header];

Add Some Content Rows

for (int i = 0; i < 10; i++) {
    MGLine *row = MGLine lineWithSize:(CGSize){320, 40}];
    row.bottomBorderColor = UIColor.lightGrayColor;
    row.padding = UIEdgeInsetsMake(0, 16, 0, 16);
    row.leftItems = (id)[NSString stringWithFormat:@"Row Number %d", i];
    row.rightItems = (id)[UIImage imageNamed:@"chevron"];
    [scroller.boxes addObject:row];
}

Layout With Animation

[scroller layoutWithDuration:0.3 completion:nil];

Layout Without Animation

[scroller layout];

Grid Layouts

The default layout algorithm places each box below the one before. To use the grid layout algorithm, change the container's contentLayoutMode.

scroller.contentLayoutMode = MGLayoutGridStyle;

Large/Dynamic Table API

For large or dynamic data sets you should use the boxProvider approach, which supports box reuse and offscreen culling. When using a boxProvider you do not add boxes directly to the container's boxes. Instead boxes are created on demand by the scroller's boxProvider, similar to the approaches taken by UITableViewDataSource and UICollectionViewDataSource.

See the MGBoxProvider interface reference in the API docs for examples of how to configure a box provider.