azamsharp azamsharp - 4 months ago 58
iOS Question

Spreadsheet Like Layout Using UICollectionView

How can I use UICollectionView to create a spreadsheet like layout where each row displays properties of a single object.


Customer Id First Name Last Name Social Address Phone

Here is what I came up with using UITableView:

funds = [[NSMutableArray alloc] init];
columnNames = [NSArray arrayWithObjects:@"fundNumber",@"fundName",@"unitPrice",@"fundBalance",@"percentageOfAccountValue",@"futureContributionAllocation", nil];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FundCell"];

Fund *fund = [funds objectAtIndex:[indexPath row]];

for(NSString *columnName in columnNames)
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, 0, 100, 44)];

label.backgroundColor = [UIColor clearColor];

label.text = [fund valueForKey:columnName];

x += label.bounds.size.width;

[cell addSubview:label];


x = 0;

return cell;

And here is the output:

enter image description here

lxt lxt

I'm not sure if you'd be able to adapt the standard flow layout - you might need to create your own UICollectionViewLayout class - but this should be fairly straightforward to do.

Like a table view, your collection view can have sections and items: each row of your spreadsheet could be a section, and then the individual elements (Last Name, Social, Address, etc) could be items.

If you want true spreadsheet like functionality (i.e, you can scroll both horizontally and vertically) then you're going to have to build your own layout class. Otherwise you may be able to adapt the existing flow layout, although arguably if you don't need to scroll you could basically achieve what you're after with a table view instead.