UITableView is probably the most used view on the iPhone. It’s flexible and the UI is ideally suited to use on the iPhone. There are lots of examples on how to add multiple items to a UITableViewCell. However, I needed to present some data in a more traditional spreadsheet style grid. The results worked well and enabled me to pack a lot of information on the screen that was very hard to follow without the vertical grid. I’ll show a very simplified version here you can use to add vertical lines to your UITableView.

First we need to create a subclass of UITableViewCell. This is so we can override drawrect and draw our lines and to add an array to hold a list of positions where we’ll draw the lines.

In this simplified example we’ll leave the positioning of the actual text in the cells in the UITableViewController and place it manually (full source code is attached at the end). We’re just providing a mechanism for drawing vertical lines to make a grid. Column locations are added by calling addColumn:

Now lets override drawRect. In it we grab the current graphics context and set the line color and width. Then we iterate over our columns array drawing a line from the top of the cell row to the bottom at each position stored in the array.

To add columns to the view just call

when you’re building each cell.

That’s it. Being a bit dense I beat my head on my desk a few days before it become obvious how blindingly simple it really was. A lot was just learning ObjectiveC and how UIKit works in general. I’m now working on a GridTableView library that will add a good bit of functionality and ease of use. I’ll post it here.

Here’s the source code.


Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注