17

Jun

Konstructor: Easy TableViews for iOS

Creating TableViews is one of the many very verbose tasks in iOS development. Every attribute of the table and the cells has to be customized by implementing a different protocol method.

Not anymore

Thanks to the magic of blocks, the overly terse task can become something declarative, readable and even fun!

Here's an example of what it can be with Konstructor:

    self.tableCellHeight = 100.0;

    /* Create an array of data.  You'll likely do this completely differently */
    NSDictionary *gloves = [NSDictionary dictionaryWithObjectsAndKeys:@"Gloves", @"name", @"for your hands", @"caption", nil];
    NSDictionary *muffs = [NSDictionary dictionaryWithObjectsAndKeys:@"Muffs", @"name", @"for your ears", @"caption", nil];
    NSDictionary *shoes = [NSDictionary dictionaryWithObjectsAndKeys:@"Socks", @"name", @"for your feets", @"caption", nil];
    NSDictionary *scarves = [NSDictionary dictionaryWithObjectsAndKeys:@"Scarves", @"name", @"for your neck", @"caption", nil];
    NSArray *items = [[NSArray alloc] initWithObjects:gloves, muffs, shoes, scarves, nil];
    
    /* Build a Table from an Array */
    [self addRowsFromArray:items withBuilder:^(id item, TableRowBuilder *builder){
        NSDictionary *current = (NSDictionary *)item;
        builder.title = [current objectForKey:@"title"];
        builder.caption = [current objectForKey:@"caption"];
        builder.iconName = @"comment_minus_48.png";
        builder.selectedIconName = @"comment_plus_48.png";
        builder.selector = @selector(toggle:);
    }];

That will give you something that looks like this:

If you want to fully customize the display of your cell, try the configurationBlock property of TableRowBuilder:

    /* Build a Table from an Array and fully customize the cell */
    [self addRowsFromArray:items withBuilder:^(id item, TableRowBuilder *builder){
        NSDictionary *current = (NSDictionary *)item;
        
        /* Fully customize the cell */
        builder.configurationBlock = ^(UITableViewCell *cell){
            UILabel *titleLabel = (UILabel *)[loadedCell viewWithTag:1];
            titleLabel.text = [current objectForKey:@"name"];
            
            UILabel *captionLabel = (UILabel *)[loadedCell viewWithTag:builder.captionTag];
            captionLabel.text = [current objectForKey:@"caption"];
            
            UIImageView *imageView = (UIImageView *)[loadedCell viewWithTag:builder.iconTag];
            imageView.image = [UIImage imageNamed:builder.selected ? @"comment_plus_48.png" : @"comment_minus_48.png"];
        };
    }];

Download, explore, fork the source on github