TweetFollow Us on Twitter

Table Techniques Taught Tastefully (part 3)

Volume Number: 18 (2002)
Issue Number: 11
Column Tag: Cocoa Development

Table Techniques Taught Tastefully (part 3)

Using NSTableView for Real-World Applications

by Dan Wood

Introduction

This is the last of a series of articles about the wonderful NSTableView class in Cocoa. While the first part went over the basics, and part the second got your hands dirty, this last part is where we pull out all the stops and do some really cool things with tables that will make you the envy of all the Cocoa programmers on your block.

In this article, we'll show you how to give your tables those trendy blue and white alternating stripes and vertical grid-lines that you see on programs like iTunes. We'll make a subclass of NSTableView that merges certain cells together across multiple columns, suitable for display of a time schedule. We'll make a custom cell to indicate relevance, like you see when you search in Apple's Mail program or the Finder. And finally, we'll see how to animate the sorting of a table, like you see in iChat. (Warning: There will be math in the last segment!)

Be sure to follow along with the "TableTester" application (downloadable at www.karelia.com/tabletester/), a program showing off most of the table features described in this series. It contains the source code corresponding to the techniques in this article as well as those in the first two parts, in case you missed them the first time around.

Striped Table Rows

If you want your table display to look like one of Apple's applications like iTunes, or just to make your list more readable, you may want to consider alternating row background colors. At first glance, it seems that the best way to accomplish this is to intercept the tableView: willDisplayCell: forTableColumn: row: delegate message and set the cell's background color depending on whether the row is even or odd. Unfortunately, this only stripes the cells with data, rather than the entire table; it also works only for text cells, not button or image cells.

A better approach is to create a subclass of NSTableView and override highlightSelectionInClipRect: (Listing 1) to draw the stripes. This method draws stripes in the background by alternating between the "even" color of light blue and the "odd" color of white.


Figure 1. Alternating Rows and Vertical Grids

Listing 1: StripedTableView.m

highlightSelectionInClipRect:
Display the background for the table in the given clipping rectangle.
- (void)highlightSelectionInClipRect:(NSRect)clipRect
{
   NSColor *evenColor   // empirically determined color, matches iTunes etc.
      = [NSColor colorWithCalibratedRed:0.929
            green:0.953 blue:0.996 alpha:1.0];
   NSColor *oddColor  = [NSColor whiteColor];
   
   float rowHeight
      = [self rowHeight] + [self intercellSpacing].height;
   NSRect visibleRect = [self visibleRect];
   NSRect highlightRect;
   
   highlightRect.origin = NSMakePoint(
      NSMinX(visibleRect),
      (int)(NSMinY(clipRect)/rowHeight)*rowHeight);
   highlightRect.size = NSMakeSize(
      NSWidth(visibleRect),
      rowHeight - [self intercellSpacing].height);
   
   while (NSMinY(highlightRect) < NSMaxY(clipRect))
   {
      NSRect clippedHighlightRect
         = NSIntersectionRect(highlightRect, clipRect);
      int row = (int)
         ((NSMinY(highlightRect)+rowHeight/2.0)/rowHeight);
      NSColor *rowColor
         = (0 == row % 2) ? evenColor : oddColor;
      [rowColor set];
      NSRectFill(clippedHighlightRect);
      highlightRect.origin.y += rowHeight;
   }
   
   [super highlightSelectionInClipRect: clipRect];
}

To mimic the iTunes look even further, you may want to draw a grid, but only the vertical lines between columns, not the horizontal lines between rows. So we override drawGridInClipRect: and provide our own implementation (Listing 2) that draws light gray vertical lines.

Listing 2: StripedTableView.m

drawGridInClipRect:
Draw the grid, but only the vertical lines.
   - (void)drawGridInClipRect:(NSRect)rect
{
   NSRange columnRange = [self columnsInRect:rect];
   int i;
   [[NSColor lightGrayColor] set];
   for (   i = columnRange.location ;
         i < NSMaxRange(columnRange) ;
         i++ )
   {
      NSRect colRect = [self rectOfColumn:i];
      int rightEdge
         = (int) 0.5 + colRect.origin.x + colRect.size.width;
      [NSBezierPath strokeLineFromPoint:
            NSMakePoint(-0.5+rightEdge, -0.5+rect.origin.y)
         toPoint:
            NSMakePoint(-0.5+rightEdge, -0.5+rect.origin.y +
               rect.size.height)];
   }
}

Voila! Striped tables, as in Figure 1. Now you can write the next iApp!

Merging table cells together

So far, all of the subclassing of NSTableView that we've done in this series are pretty straightforward, and modify the default behavior only subtly. But what happens when the class is radically subclassed? Well, one example of this is Cocoa's own NSOutlineView, a subclass that barely resembles its parent in the way that it structures and presents its contents. In this segment, we'll try something a bit less ambitious, but significant nevertheless.

The challenge is this: to have a table view in which certain columns are merged together with their neighboring columns. An example application would be a daily schedule in which appointments take a variable amount of time. You want the cells to span across multiple columns, not constrained to individual columns. (Readers familiar with HTML can equate this to the "colspan" attribute of a <TD> tag.)

There are two sides to making this work. One is to modify the controller code that provides the data for the table to display; the other is to implement the view (the NSTableView subclass, which we call MergedColumnTableView) to display the data provided by the controller.

For the controller, we invent a new method for an informal protocol for your controller to define:

(int)tableView:(NSTableView *)tableView
   spanForTableColumn:(NSTableColumn *)tableColumn
   row:(int)row;

Our implementation should return 1 if the cell is one column wide (the usual case); 0 if no data is to be shown in the column (generally the case if it is to the right of a multiple-cell-spanning table), and a number greater than 1 if the cell is to span more than one column to the right. Because we pass in a pointer to the table view, this method can be used even if there is more than one table that your controller controls; because we pass in a row number, each row can have differ in its presentation.

The TableTester application accompanying this article reads in a sample "class schedule" from a property list file, and implements the standard NSTableView data source methods of numberOfRowsInTableView: and tableView:objectValueForTableColumn:row: as well as the spanning method for this protocol. We won't be examining the controller implementation in-depth here, since its very dependent on the data structure. Unlike a typical table display, where an array of dictionaries will usually suffice, the data to display is more complex. So if you need to display data that spans multiple columns, you can take advantage of MergedColumnTableView, but you are on your own for implementing the controller. (This is yet another reason why it's good to partition the view, the controller, and the model!)

How the MergedColumnTableView subclassing works, on the other hand, is significant, because it may help reveal techniques that you can use for other table subclassing needs. We override three methods of NSTableView: frameOfCellAtColumn: row:, to override the rectangle for a given cell to take the column spanning into account; drawRow: clipRect:, to manage the drawing of all the columns in a row; and drawGridInClipRect:, to draw the table grid lines in such a way that merged cells have no grid line between them. (Each of those methods provides a special behavior if the data source implements our additional method; if not, the superclass provides the default behavior.)

The most important override is frameOfCellAtColumn:row:. (See Listing 3.) This is the method that calculates the rectangle associated with a given cell for each column and row. Since our goal is to make the cells wider than they would normally be, this is the logical place to modify the default table behavior. All we have to do is find out the number of columns that the given cell should span, and return an appropriate rectangle. If the column span is zero, we return an empty rectangle, NSZeroRect. If the column span is one, we let the superclass calculate the rectangle, since nothing is different about a cell with a column span of one. If the column span is greater than one, we collect up all the rectangles of the current cell and the cells to the right by invoking the superclass's method, merging the rectangles together into one bigger rectangle.

Listing 3: MergedColumnTableView.m

frameOfCellAtColumn:row:
Return the rectangle for the given cell.  This may behave like its superclass, or it may return an 
empty rectangle or a wider rectangle if the table's column span is not one.

- (NSRect)frameOfCellAtColumn:(int)column row:(int)row
{
   int colspan;
   if (![[self dataSource]
      respondsToSelector:
         @selector(tableView:spanForTableColumn:row:)])
   {
      return [super frameOfCellAtColumn:column row:row];
   }
   colspan = [[self dataSource]
            tableView:self
            spanForTableColumn:
               [[self tableColumns] objectAtIndex:column]
            row:row];
   if (0 == colspan)
   {
      return NSZeroRect;
   }
   if (1 == colspan)
   {
      return [super frameOfCellAtColumn:column row:row];
   }
   else      // 2 or more, it's responsibility of data source to provide reasonable number
   {
      NSRect merged
         = [super frameOfCellAtColumn:column row:row];
      // start out with this one
      int i;
      for (i = 1; i < colspan; i++ )   // start from next one
      {
         NSRect next
            = [super frameOfCellAtColumn:column+i row:row];
         merged = NSUnionRect(merged,next);
      }
      return merged;
   }
}

The above override covers most of the needed functionality, but a couple of subtle items remain. When horizontal scrollbars are used in the table, you will find that some table cells don't get drawn on the left edge of the table. This is because the standard NSTableView draws only the cells that are currently visible within the NSScrollView, and it doesn't realize that a cell spanning multiple columns needs to be drawn even if it starts to the left of the visible rectangle. (See Figure 2.) So we override drawRow: clipRect: (Listing 4) to look at the leftmost column, and if the cell there has a column span of zero, it needs to "back up" to the left and find the cell that spans multiple columns. Once it finds that cell, it expands the clipping rectangle so that the wide cell will be drawn and thus appear in the visible region.


Figure 2. Missing Columns

Listing 4: MergedColumnTableView.m

typeAheadString:inTableView:
Actually select the appropriate row based upon the string that has been typed.
- (void)drawRow:(int)inRow clipRect:(NSRect)inClipRect
{
   NSRect newClipRect = inClipRect;
   if ([[self dataSource]
      respondsToSelector:
         @selector(tableView:spanForTableColumn:row:)])
   {
      int colspan = 0;
      int firstCol
         = [self columnsInRect:inClipRect].location;
      // Does the FIRST one of these have a zero-colspan?  If so, extend range.
      while (0 == colspan)
      {
         colspan = [[self dataSource]
                     tableView:self
                     spanForTableColumn:[[self tableColumns]
                        objectAtIndex:firstCol]
                     row:inRow];
         if (0 == colspan)
         {
            firstCol--;
            newClipRect = NSUnionRect(newClipRect,
               [self frameOfCellAtColumn:firstCol row:inRow]);
         }
      }
   }
   [super drawRow:inRow clipRect:newClipRect];
}


Figure 3: The grid lines don't look right.

With the above override, all of the cells will display, but what if you want to display a grid to make the cell sizes clearer? If we use the standard grid, the table would look like Figure 3, with vertical lines cutting across our wide cells. So we implement a new grid that takes the column spans into account, drawing vertical lines only before or after cells. If you have a "sparse" display (such as the example class schedule here), it looks even better if you give the table a distinguishing background color. The final result is in Figure 4.


Figure 4: Grid lines match the column span.

The drawGridInClipRect: override (Listing 5) determines all of the rows and columns that will need to be drawn for the given clipping rectangle. It then loops first through each row, drawing the horizontal lines using NSBezierPath methods, then loops through each row's columns to draw the vertical lines. Similarly to the frameOfCellAtColumn:row: override, it builds up the rectangle for a cell spanning multiple columns by growing a rectangle using the NSUnionRect operation.

Listing 5: MergedColumnTableView.m

typeAheadString:inTableView:
Actually select the appropriate row based upon the string that has been typed.

- (void)drawGridInClipRect:(NSRect)rect
{
   if (![[self dataSource] respondsToSelector:
      @selector(tableView:spanForTableColumn:row:)])
   {
      [super drawGridInClipRect:rect];
   }
   else
   {
      NSRange rowRange = [self rowsInRect:rect];
      NSRange columnRange = [self columnsInRect:rect];
      int row;
      // Adjust column range, always go from zero, so we can gather columns even to 
      // the left of what we are supposed to draw.
      columnRange = NSMakeRange(0,NSMaxRange(columnRange));
      [[NSColor grayColor] set];
      for (   row = rowRange.location ;
            row < NSMaxRange(rowRange) ;
            row++ )
      {
         int col = columnRange.location;
         int oldLeftEdge
            = 0.5 + [self rectOfColumn:col].origin.x;
         NSRect rowRect = [self rectOfRow:row];
         // here, frame not the top and not the left, but the bottom
         [NSBezierPath strokeLineFromPoint:
            NSMakePoint(rowRect.origin.x,
               -0.5+rowRect.origin.y+rowRect.size.height)
            toPoint:
            NSMakePoint(rowRect.origin.x + rowRect.size.width,
               -0.5+rowRect.origin.y+rowRect.size.height)];
         while (   col < NSMaxRange(columnRange) )
         {
            int colspan = [[self dataSource] tableView:self
               spanForTableColumn:[[self tableColumns]
                  objectAtIndex:col] row:row];
            NSRect gridRect = NSZeroRect;
            if (0 == colspan)
            {
               col++;      // no grid here, move along
            }
            else   // Now gather up the next <colspan> rectangles
            {
               int i, rightEdge, leftEdge;
               for ( i = 0 ; i < colspan ; i++ )
               {
                  NSRect thisRect = NSIntersectionRect(
                     [self rectOfColumn:col+i],
                     [self rectOfRow:row]);
                  gridRect = NSUnionRect(gridRect,thisRect);
               }
               col += colspan;
               // left edge.  Only draw if this left edge isn't one we just drew.
               leftEdge = (int) 0.5 + gridRect.origin.x;
               if (leftEdge != oldLeftEdge)
               {
                  [NSBezierPath strokeLineFromPoint:
                     NSMakePoint(
                        -0.5+leftEdge, -0.5+gridRect.origin.y)
                     toPoint:
                     NSMakePoint(-0.5+leftEdge,
                        -0.5+gridRect.origin.y
                        + gridRect.size.height)];
               }
               // right edge
               rightEdge = (int) 0.5 + gridRect.origin.x
                  + gridRect.size.width;
               [NSBezierPath strokeLineFromPoint:
                  NSMakePoint(-0.5+rightEdge,
                     -0.5+gridRect.origin.y)
                  toPoint:
                  NSMakePoint(-0.5+rightEdge,
                     -0.5+gridRect.origin.y
                     + gridRect.size.height)];
               oldLeftEdge = rightEdge;   // save edge for next pass through.
            }
         }
      }
   }
}

That's all there is to it. OK, maybe that one wasn't so easy. If you are going to be heavily subclassing NSTableView, realize that it is going to take a lot of trial and error, research, and help from other smart people to get it to work just right. Subclassing any object for which you don't have the source code is never easy, because you don't know all of the subtle interactions among the methods that you might be able to see if it was your code. Still, it is possible to modify NSTableView's default behavior by modifying just a few methods.

Custom Cell Classes

That last one was a bit deep, so let's take a breather and try something a little easier. How do you make a "relevance" indicator, like you see when you search for items in the Finder? (See Figure 5.) As of Mac OS X 10.2, there is now a standard widget you need to use, but no such class has been provided in Cocoa for us to use. Since a Table displays cells, we need to make our own custom subclass of NSCell. We'll call the class "RankCell" because it's easier to spell than "RelevanceCell." (See Listing 6.)


Figure 5: Relevance cells in a table

Listing 6: RankCell.m

// declare a static variable that will hold the pattern.
static NSImage *sRankPatternImage = nil;
initialize
When the class is initialized, load in the striped pattern from an image in the project.

+ (void) initialize
{
   sRankPatternImage
      = [[NSImage imageNamed:@"stripe"] retain];
}

floatValue
Return the value of the cell (a number from 0.0 to 1.0) as a floating point number.  The method 
verifies that the cell's associated object value is indeed an object that can return a float. (Both 
NSNumber and NSString respond to floatValue!)

- (float) floatValue
{
   float result = 0.0;
   id objectValue = [self objectValue];
   if ([objectValue respondsToSelector:
      @selector(floatValue)])
   {
      result = [(NSNumber *)objectValue floatValue];
   }
   return result;
}

setFloatValue:

Set the value of the cell to a number between 0.0 and 1.0.

- (void) setFloatValue:(float)inValue
{
   float value = inValue;
   if (value > 1.0) value = 1.0;
   if (value < 0.0) value = 0.0;
   [self setObjectValue:[NSNumber numberWithFloat:value]];
}

drawInteriorWithFrame: inView:

Draw the cell. The cell will be smaller if its controlSize is NSSmallControlSize.

(void) drawInteriorWithFrame: (NSRect)inFrame
      inView: (NSView*)inView;
{
   float drawWidth;
   NSRect fillFrame, eraseFrame;
   // Constrain the frame's height
   float yInset
      = (NSSmallControlSize == [self controlSize])
         ? 4.0 : 3.0;
   NSRect newFrame = NSInsetRect(inFrame, 3.0, yInset);
   // Calculate width of filled part
   drawWidth
      = floor([self floatValue] * newFrame.size.width);
   if (drawWidth < 1)
   {
      drawWidth = 1;   //  at least 1 pixel wide, so we see something!
   }
   NSDivideRect(newFrame, &fillFrame, &eraseFrame,
      drawWidth, NSMinXEdge);
   [[NSColor colorWithPatternImage:sRankPatternImage] set];
   [NSBezierPath fillRect:fillFrame];
}

All we need to do is to set our table to use our RankCell class. As usual, a good place to do this is in an awakeFromNib method. (See Listing 7.) Then you have your data source's tableView: objectValueForColumn: row: method return an NSNumber between 0.0 and 1.0. That's it!

Listing 7: CellDelegate.m

awakeFromNib
Create a RankCell and set it as a column's cell.
- (void)awakeFromNib
{
   RankCell    *rankCell
      = [[[RankCell alloc] init] autorelease];
   NSTableColumn *rankColumn
      = [oTable tableColumnWithIdentifier:@"rank"];
   [rankCell setControlSize:NSSmallControlSize];
   [rankColumn setDataCell:rankCell];
}

Animated Sorting

If you've seen iChat, you have probably noticed the slick animation when people on your Buddy List change status. The table elements animate as they move around. Very slick, but how did they do it? It probably involved subclassing NSTableView. Inspired by some Apple sample code called "AnimatedSlider" that animates the transition between values of an NSSlider (much like the preset equalizer settings in iTunes), I've determined out how to do this, and I present the technique here. (It's hard to show animations in print, but Figure 6 should give you an idea of what it looks like.)


Figure 6: Animated Sorting: Before, During, and After

The trick is to override the NSTableView method rectOfRow: and invoke it multiple times over a second or so, to move the rows from their old positions to their new ones. Unlike the "AnimatedSlider" example, which managed to put all the animation functionality into a category method on NSSlider, this is a little bit more complex, so we need the controller involved as well. So to keep the view separated as much as possible from the controller, the NSTableView subclass--AnimatedTableView--lets its delegate (or its data source, if you desire) take care of the logic associated with the animation. (See Listing 8.)

Listing 8: AnimatedTableView.m

rectOfRow:
Override NSTableView's method that calculates the rectangle of a given row.  Let the delegate 
determine what the rectangle for a given row is, if that delegate responds to the selector to do so.  
If animation is going on, it will probably return a value other than the default.

- (NSRect)rectOfRow:(int)rowIndex
{
   NSRect theDefaultRect = [super rectOfRow:rowIndex];
   if ([[self delegate] respondsToSelector:
            @selector(tableView:rectOfRow:defaultRect:)])
   {
      return [[self delegate]
         tableView:self rectOfRow:rowIndex
         defaultRect:theDefaultRect];
   }
   else
   {
      return theDefaultRect;
   }
}

unanimatedRectOfRow:
Return the default NSTableView's version of the rectangle for a given row; this method is provided so 
we can determine the rectangle as if animation weren't happening.

- (NSRect)unanimatedRectOfRow:(int)rowIndex
{
   return [super rectOfRow:rowIndex];
}

rowsInRect:
Override NSTableView's method that determines what rows are visible for a given rectangle.  Let the 
delegate determine what the range of rows is for a given rectangle, if that delegate responds to the 
selector to do so.  If animation is going on, it will probably return a value other than the default.

- (NSRange)rowsInRect:(NSRect)inRect
{
   NSRange theDefaultRange = [super rowsInRect:inRect];
   if ([[self delegate] respondsToSelector:
            @selector(tableView:rowsInRect:defaultRange:)])
   {
      return [[self delegate]
         tableView:self rowsInRect:inRect
         defaultRange:theDefaultRange];
   }
   else
   {
      return theDefaultRange;
   }
}

In order to animate the rows in a table, we need to keep track of both the original positions and the new positions of each row in the table! One way to do this is to build a new array of index values so we can lookup the original array position for any row in the sorted array. For example, if an array containing E, G, B, D, F is sorted into B, D, E, F, G, then we could build an array containing 2, 3, 0, 4, 1. Element 0 of the new array, B, used to be at position 2 in the old array; Element 1, D, used to be at position 3, and so forth. And what better way to implement this using a category method on NSArray! (See Listing 9.)

Listing 9: SortingDelegate.m

@interface NSArray (findPositions)
(NSArray *)
      findPositionsInUnsortedArray:(NSArray *)fromArray;
@end
@implementation NSArray (findPositions)
findPositionsInUnsortedArray:
Build an array of NSNumbers, representing the position each item of an array used to be before it was sorted.
(NSArray *)
      findPositionsInUnsortedArray:(NSArray *)fromArray
{
   NSMutableArray *result
      = [NSMutableArray arrayWithCapacity:[self count]];
   NSEnumerator *theEnum = [self objectEnumerator];
   id object;
   while (nil != (object = [theEnum nextObject]) )
   {
      int indexInOld = [fromArray indexOfObject:object];
      [result addObject:[NSNumber numberWithInt:indexInOld]];
   }
   return result;
}
@end

Now it's time for the actual animation, defined in SortingDelegate.m. (Note that this class contains three relevant instance variables: mTimer, a reference to the NSTimer used for sorting; mOldPositionsArray, the lookup array described above; and mAnimationPosition, a floating point value representing how far along in the animation we are.) Let's dive right into Listing 10 for the methods we need.

Listing 10: SortingDelegate.m

// The "frame rate" for animating the table sort.
const float kFrameRate = 1.0/30;
// Duration of the animation, probably shouldn't be more than a second.
const float kAnimationTime = 0.75;    
setOldPositionsArray:
Set the array that holds the old positions of the items before they were sorted.
- (void) setOldPositionsArray:(NSArray *)inNewValue
{
   [inNewValue retain];
   [mOldPositionsArray release];
   mOldPositionsArray = inNewValue;
}

stopAnimating
Remove any animating NSTimer.  Also clears mAnimationPosition to indicate that we are no longer 
animating.

- (void) stopAnimating
{
   [mTimer invalidate];
   mTimer = nil;
   mAnimationPosition = 0;
}
setTimer:
Set the animation timer, replacing any existing one.
- (void) setTimer:(NSTimer *)inNewValue
{
   [inNewValue retain];
   [mTimer release];
   [self stopAnimating];
   mTimer = inNewValue;
}

tableView:rowsInRect:defaultRange:
Invoked by AnimatedTableView.  If we're currently animating, we just return the entire range of all 
rows, so that all rows get drawn no matter where they are.  (They will still be clipped properly, but 
if we don't override this, then some rows may not be drawn.)  There are probably ways to make this 
more efficient, calculating which rows need to be displayed, but as long as our table isn't too big, 
this should be fine.

- (NSRange)tableView:(AnimatedTableView *)inTableView
      rowsInRect:(NSRect)inRect
      defaultRange:(NSRange)inDefaultRange
{
   if (mAnimationPosition > 0)      // are we currently animating?
   {
      return NSMakeRange(0, [oData count]);   // just return all rows
   }
   else
   {
      return inDefaultRange;
   }
}

tableView: rectOfRow: defaultRect:
Invoked by AnimatedTableView.  Returns a rectangle for the given row in the table.  If we are 
animating, we calculate a rectangle to be be some percentage of the way between the row's old 
rectangle and its new rectangle.

(NSRect)tableView:(AnimatedTableView *)inTableView
      rectOfRow:(int)inRowIndex
      defaultRect:(NSRect)inDefaultRect
{
   if (mAnimationPosition > 0)   // are we currently animating?
   {
      // Get the rectangles of where the row originally was, and where it will end up.
      int oldPosition = [[mOldPositionsArray
         objectAtIndex:inRowIndex] intValue];
      NSRect oldR
         = [inTableView unanimatedRectOfRow:oldPosition];
      NSRect newR
         = [inTableView unanimatedRectOfRow:inRowIndex];
      // t will be our fraction between 0 and 1 of how far along the row should be.
      float t = mAnimationPosition;      // linear position based on time
      // Calculate a rectangle between the original and the final rectangles.
      NSRect newRect = NSMakeRect(
         NSMinX(oldR) + (t * (NSMinX(newR) - NSMinX(oldR))),
         NSMinY(oldR) + (t * (NSMinY(newR) - NSMinY(oldR))),
         NSWidth(newR), NSHeight(newR) );
      return newRect;
   }
   else
   {
      return inDefaultRect;   // not animating, just return the standard value.
   }
}

animateStep:
Invoked by the NSTimer multiple times to handle the animation.  Calculate the position we are based on
the current time, and then either force a display of the table, or stop the animation.

- (void) animateStep:(NSTimer *)inTimer
{
   NSDate *start = [inTimer userInfo];
   NSTimeInterval elapsed
      = fabs([start timeIntervalSinceNow]);
   mAnimationPosition = MIN(1.0 , elapsed / kAnimationTime);
   // Done yet?  Allow a bit of "servo jitter" to allow for floating-point messiness
   if (fabs(mAnimationPosition - 1.0) <= 0.01)  
   {
      [self stopAnimating];
      [oTable display];      // force a display of the table in its normal state
   }
   else
   {
      [oTable display];      // force a display of the table in its new state.
   }
}

tableView: animateSortFromArray: toArray:
Initiate an animated sort.  We pass in the old array before the sort, and the new sorted array.  It 
kicks off a timer to start the animation with the current date/time passed in as user info so it can
keep track of how far along the animation it is.

(void)tableView:(NSTableView *)inTableView
      animateSortFromArray:(NSArray *)fromArray
      toArray:(NSArray *)toArray
{
   NSTimer *timer;
   NSRange visibleRows;
   [self stopAnimating];  // Stop any existing sort animation
   [self setOldPositionsArray:
      [toArray findPositionsInUnsortedArray:fromArray]];
   timer =
      [NSTimer scheduledTimerWithTimeInterval:kFrameRate
         target:self
         selector:@selector(animateStep:)
         userInfo: [NSDate date]   // store the starting date as user info
         repeats:YES];
   [self setTimer:timer];   // store the timer so we can stop it when done.
}

sortData
Actually sort the data.  This is an extension of the sortData method described in part 2 of this 
series.  For this sample, if the application delegate method animateSorts returns YES, then kick off 
the sort.  Otherwise, sort without animation.  In either case, the table selection is preserved across
the sort so that any rows selected before the sort will be properly selected in their new positions 
after the sort.

- (void) sortData
{
   SortContext ctxt={ mSortingKey, mSortDescending };
   NSSet *oldSelection
      = [self saveSelectionFromTable:oTable];
   if ([[NSApp delegate] animateSorts])
   {
      NSArray *originalOrderArray = [oData copy];
      [oData sortUsingFunction:ORDER_BY_CONTEXT
            context:&ctxt];
      [self restoreSelection:oldSelection toTable:oTable
         refresh:NO];
      [self tableView:oTable
         animateSortFromArray:originalOrderArray
         toArray:oData];
      // When done, the data should be displayed correctly.
   }
   else
   {
      [oData sortUsingFunction:ORDER_BY_CONTEXT
         context:&ctxt];
      [oTable reloadData];
      [self restoreSelection:oldSelection toTable:oTable
         refresh:YES];
   }
}

That's all that's needed for a basic animated sort. You may find that you need to implement your own animation code differently to deal with your application's specific needs, but this should give you the basic idea. You are warned: This is not going to work very well on very large tables, since the position of every row in the table is being calculated repeatedly, regardless of whether it is visible or not. But for reasonable sizes, the animation can add a nice extra dimension to your interface.

There are a couple of visual improvements that can be made to the animation, however. The first improvement, demonstrated in the AnimatedSlider example, is making the movement seem more natural by letting the movement accelerate rather than abruptly changing from standing still to moving full-speed. Currently, the Y value (vertical position) changes linearly with respect to time, as depicted mathematically in Figure 7. It is possible to adjust the position by inserting a sine function into the calculations to ease the transition. Listing 11 shows the function to convert a value between 0.0 and 1.0 into its eased equivalent, depicted in Figure 8. All we need to do is insert t = easeFunction(t); into tableView: rectOfRow: defaultRect:.


Figure 7: Linear Movement


Figure 8: A Sine wave eases the transition.

Listing 11: SortingDelegate.m

easeFunction
This function implements a sinusoidal ease-in/ease-out for t = 0 to 1.0.  T is scaled to represent 
the interval of one full period of the sine function, and transposed to lie above the X axis.

float easeFunction(float t)
{
   return (sin((t * M_PI) - M_PI_2) + 1.0 ) / 2.0;
}

The other visual improvement that can be made is only apparent when you animate the reversal of a sort, changing from ascending to descending sort order, or vice-versa. Since the first items in the table exchange themselves symmetrically with the last items, they all end up bunching together in the center of the table halfway through the process. (See Figure 9.) It doesn't look as cool as it could. How can we make the movement a little bit less symmetrical so that everything doesn't crowd the middle of the table?


Figure 9: Reversing sort order bunches up in the middle.

If we could vary the "speed" of each row so that the rows at the top of the table move at a different rate than the rows at the bottom of the table, this would prevent the traffic jam in the center of the table. One way to do this is to use a "curve" function to move rows, with a different parameter used for each row. A reasonable function is shown in Figure 9. All we need to do is vary the power (n). Rows at one end of the table use a value slightly less than one; the middle row uses a power of one (a straight line); Rows at the other end of the table use a value slightly greater than one. We get a different curve for each row, and each row moves at a different rate.


Figure 10: Power function with varying values of n

The effect of this is very nice; it looks as if the rows are doing a "back flip" as they swap their positions. Figure 11 might give you a sense of how it looks, but it's more fun to see it in the program itself.


Figure 11: Adding a "curve" makes a reversal look nicer.

If you happen to be viewing only a piece of a table--say, the top half or the bottom half--and the rest is scrolled out of view, It can look pretty strange for the rows to move out of view and then move back into view a moment later. So we can perform an adjustment to the swapping behavior so that the curve is "centered" on the half of the table that you are looking at. So if you are viewing the top half of a table, the curve will be flipped compared to viewing the bottom half of a table.

Listing 12 shows the function you need to convert the "t" value into its curved counterpart.

Listing 12: SortingDelegate.m

// How "curvy" the movement should be. 0.2 or 0.3 is a nice value; 0.5 is funky!
const float kCurve = 0.3; 
curveFunction

This function is used to de-center t (from 0 to 1.0) by a power p (a reasonable range is 0.8 to 1.2).
It will make the animated reordering a little more interesting to watch.

float curveFunction (float t, float p)
{
   return pow( 1 - pow((1-t),p) , 1/p );
}

You will need to determine if the user is viewing only the top half of the table before you kick off the timer in tableView: animateSortFromArray: toArray:. This code just checks if the topmost visible row is less than 0.6 times the number of rows.

visibleRows = [inTableView rowsInRect:[inTableView visibleRect]];
mViewingTop
   = NSMaxRange(visibleRows) < 0.6 * [fromArray count];

You need to insert the following lines into tableView: rectOfRow: defaultRect:.

float rowPos = ((float) inRowIndex / [oData count]);
// fractional position of row in table
float rowPosAdjusted
   = mViewingTop ? (1.0 - rowPos) : rowPos;
float p = rowPosAdjusted * (kCurve*2.0) + 1.0 - kCurve;
// e.g. 0 -> 0.8; n/2 -> 1.0; n -> 1.2
// (p actually could range from 1.0+kCurve to its reciprocal to be truly symmetrical)
t = curveFunction(t, p);

To bring this all together, we really want to have both the curve and the sinusoidal movement. So when we invoke curveFunction and then easeFunction together, we get movement as depicted in Figure 12. What more could you ask for?


Figure 12: Combining the power and the sine functions

Conclusion

Whew! That has been a long trip through Table Land. Hopefully you feel armed with just about everything you need to make your application really shine. Quite a bit of code needs to be added to a simple NSTableView to get all the bells and whistles in place, but it's still possible to keep a clean separation between your views and your controllers. Accessing your data from the controllers is still quite simple thanks to Cocoa's Foundation Kit.

If you want to take advantage of many of these features, you will find yourself needing to implement several data source and delegate methods, and probably build a subclass for your table view that is an amalgamation of the subclasses presented here. And example subclass might be DeletableStripedTypeaheadAnimatedSortingTableView, but you are of course welcome to invent a shorter class name. (Never use a long word when you can use a diminutive one!)

Further Reference

Many of these techniques are discussed on the two dominant Cocoa discussion lists, at Apple (http://lists.apple.com/mailman/listinfo/cocoa-dev) and OmniGroup (http://www.omnigroup.com/developer/mailinglists/macosx-dev/). A great way to search the archives of these lists is to use http://cocoa.mamasam.com. Search the archives and post questions to these lists if you are attempting to do something with NSTableView that isn't discussed here.

The Web holds other resources related to NSTableView as well. NSTableView is discussed on cocoadev.com; Stone Design (http://www.stone.com/dev/) has a subclass available online; OmniGroup (http://www.omnigroup.com/developer/sourcecode/) has a number of extensions in their OmniAppKit code; Stephane Sudre has some good NSTableView articles (in French) at http://www.mosx.net/dev/.


Dan Wood, the son of an organic cropduster pilot and a neurosurgeon, grew up in Amish Pennsylvania, back in the roaring twenties. As a child, he watched Lost in Space and Powerpuff Girls on TV. After graduating with a degree in Chocolatology from the University of Hershey, Dan joined the Peace Corps, teaching American Sign Language to underprivileged dolphins. He is currently a road crew foreman for the California Department of Transportation (CalTrans), and has written a successful application in Cocoa called Watson. Dan thanks Chuck Pisula at Apple for his technical help with this series, and acknowledges online code fragments from John C. Randolph, Stephane Sudre, Ondra Cada, Vince DeMarco, Harry Emmanuel, and others. You can reach him at dwood@karelia.com.

 
AAPL
$97.19
Apple Inc.
+2.47
MSFT
$44.87
Microsoft Corpora
+0.04
GOOG
$595.98
Google Inc.
+1.24

MacTech Search:
Community Search:

Software Updates via MacUpdate

Firefox 31.0 - Fast, safe Web browser. (...
Firefox for Mac offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals... Read more
Little Snitch 3.3.3 - Alerts you to outg...
Little Snitch gives you control over your private outgoing data. Track background activityAs soon as your computer connects to the Internet, applications often have permission to send any... Read more
Thunderbird 31.0 - Email client from Moz...
As of July 2012, Thunderbird has transitioned to a new governance model, with new features being developed by the broader free software and open source community, and security fixes and improvements... Read more
Together 3.2 - Store and organize all of...
Together helps you organize your Mac, giving you the ability to store, edit and preview your files in a single clean, uncluttered interface. Smart storage. With simple drag-and-drop functionality,... Read more
Cyberduck 4.5 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
iExplorer 3.4 - View and transfer all th...
iExplorer is an iPhone browser for Mac lets you view the files on your iOS device. By using a drag and drop interface, you can quickly copy files and folders between your Mac and your iPhone or... Read more
Airmail 1.4 - Powerful, minimal email cl...
Airmail is a powerful, minimal mail client.It was designed to retain the same experience with a single or multiple accounts and provide a quick, modern and easy-to-use user experience. Airmail... Read more
Macs Fan Control 1.1.12 - Monitor and co...
Macs Fan Control allows you to monitor and control almost any aspect of your computer's fans, with support for controlling fan speed, temperature sensors pane, menu-bar icon, and autostart with... Read more
A Better Finder Rename 9.37 - File, phot...
A Better Finder Rename is the most complete renaming solution available on the market today. That's why, since 1996, tens of thousands of hobbyists, professionals and businesses depend on A Better... Read more
MacBook Air EFI Firmware Update 2.9 - Fo...
MacBook Air EFI Firmware Update is recommended for MacBook Air (Mid 2011) models. This update addresses an issue where systems may take longer to wake from sleep than expected and fixes a rare issue... Read more

Latest Forum Discussions

See All

Traps n' Gemstones (Games)
Traps n' Gemstones 1.00 Device: iOS Universal Category: Games Price: $2.99, Version: 1.00 (iTunes) Description: LAUNCH SALE! 40% off, JULY ONLY! TRAPS N' GEMSTONES is an adventurous platform game, among gamers typically known as the... | Read more »
Soccer Physics (Games)
Soccer Physics 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: One-button soccer game! So dumb it's fun. "Soccer Physics is probably the funniest football game you'll play on iOS" —... | Read more »
Ex-Angry Birds Developers Release Monsu...
Ex-Angry Birds Developers Release Monsu Teaser Trailer Posted by Jennifer Allen on July 23rd, 2014 [ permalink ] Finnish developer Boomlagoon has released a teaser trailer of their forthcoming side-scrolling action platformer, | Read more »
Lots of New Modes Have Been Added to Can...
Lots of New Modes Have Been Added to Canabalt Posted by Jennifer Allen on July 23rd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Stronghold 3: The Campaigns Review
Stronghold 3: The Campaigns Review By Jennifer Allen on July 23rd, 2014 Our Rating: :: DULL STRATEGIZINGiPad Only App - Designed for the iPad A cumbersome strategy game, Stronghold 3: The Campaigns has a few too many issues to... | Read more »
Table Tennis Touch on Sale for a Limited...
Table Tennis Touch on Sale for a Limited Time Posted by Jessica Fisher on July 23rd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Secret Files Tunguska Review
Secret Files Tunguska Review By Jennifer Allen on July 23rd, 2014 Our Rating: :: CONSPIRACY-LITTERED ADVENTURINGUniversal App - Designed for iPhone and iPad Offering traditional adventuring with no fear of in-app purchases, Secret... | Read more »
Celebrate Summer With a Cat in the Hat L...
Celebrate Summer With a Cat in the Hat Learning Library Sale Posted by Ellis Spice on July 22nd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Dragon Raiders Review
Dragon Raiders Review By Nadia Oxford on July 22nd, 2014 Our Rating: :: RUN, DRAGON, RUNUniversal App - Designed for iPhone and iPad Dragon Raiders is rough and scaly in some parts, but overall it’s an enjoyable level-based running... | Read more »
MyTaskList Review
MyTaskList Review By Jennifer Allen on July 22nd, 2014 Our Rating: :: EFFECTIVE IF PLAINUniversal App - Designed for iPhone and iPad It’s not the most stylish of task management apps, but MyTaskList has all the features you could... | Read more »

Price Scanner via MacPrices.net

With The Apple/IBM Alliance, Is The iPad Now...
Almost since the iPad was rolled out in 2010, and especially after Apple made a 128 GB storage configuration available in 2012, there’s been debate over whether the iPad is a serious tool for... Read more
MacBook Airs on sale starting at $799, free s...
B&H Photo has the new 2014 MacBook Airs on sale for up to $100 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels... Read more
Apple 27″ Thunderbolt Display (refurbished) a...
The Apple Store has Apple Certified Refurbished 27″ Thunderbolt Displays available for $799 including free shipping. That’s $200 off the cost of new models. Read more
WaterField Designs Unveils Cycling Ride Pouch...
High end computer case and bag maker WaterField Designs of San Francisco now enters the cycling market with the introduction of the Cycling Ride Pouch – an upscale toolkit with a scratch-free iPhone... Read more
Kingston Digital Ships Large Capacity Near 1T...
Kingston Digital, Inc., the Flash memory affiliate of Kingston Technology Company, Inc.,has announced its latest addition to the SSDNow V300 series, the V310. The Kingston SSDNow V310 solid-state... Read more
Apple’s Fiscal Third Quarter Results; Record...
Apple has announced financial results for its fiscal 2014 third quarter ended June 28, 2014, racking up quarterly revenue of $37.4 billion and quarterly net profit of $7.7 billion, or $1.28 per... Read more
15-inch 2.0GHz MacBook Pro Retina on sale for...
B&H Photo has the 15″ 2.0GHz Retina MacBook Pro on sale for $1829 including free shipping plus NY sales tax only. Their price is $170 off MSRP. B&H will also include free copies of Parallels... Read more
Apple restocks refurbished Mac minis for up t...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Twelve South HiRise For MacBook – Height-Adju...
If you use your MacBook as a workhorse desktop substitute, as many of us do, a laptop stand combined with an external keyboard and pointing device are pretty much obligatory if you want to avoid... Read more
Why The Mac Was Not Included In The Apple/IBM...
TUAW’s Yoni Heisler cites Fredrick Paul of Network World whoi blogged last week that the Mac’s conspicuous absence from Apple and IBM’s landmark partnership agreement represents a huge squandered... Read more

Jobs Board

*Apple* Sales Chat Rep - Apple (United State...
…is looking for motivated, outgoing, and tech savvy individuals who want to offer Apple Customers an unparalleled customer experience over chat. At Apple , we believe Read more
Mac Expert - *Apple* Online Store Mexico -...
…MUST be fluent in English and Spanish to be considered for this position At Apple , we believe that hard work, a fun environment, creativity and innovation fuel the Read more
*Apple* Industrial Design CAD Sculptor - App...
**Job Summary** The Apple Industrial Design team is looking for a CAD sculptor/Digital 3D modeler to create high quality CAD models used in the industrial design process Read more
*Apple* Developer Support Advisor - Portugue...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Sr Software Lead Engineer, *Apple* Online S...
**Job Summary** The Apple Online Store is looking for a highly motivated, entrepreneurial senior software engineer to join the Apple Online Store Publishing Systems Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.