Simple slide-open table view cells

This page has been archived

This article contains out of date information and is preserved for historical purposes only.

26 May 2011 Simple slide-open table view cells

Twitter for iPhone (formerly Tweetie) has long been one of my favourite iOS Twitter clients (#dickbar fiasco not withstanding) and has some innovative UI features, particularly it's much imitated "pull-to-refresh" behaviour.

One particular feature I like is the ability to swipe on a tweet to reveal contextual buttons underneath. Like a lot of gestural UI patterns, it does suffer from lack of discoverability but as a shortcut to common operations it's a nice power feature that makes it possible to fit more UI within the constraints of the iPhone's relatively small screen space.

LRSlidingTableViewCell is my attempt at creating a reusable sliding table view cell that you can use in your projects - as with most of my open source code, it's released under the MIT license and while you do not have to, a credit within your app if you use this is always appreciated.

Using the cell is straightforward; it's API is simple and can generally be used as a drop-in replacement for a standard UITableViewCell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *identifier = @"CELL_IDENTIFIER";
  
  LRSlidingTableViewCell *cell = (LRSlidingTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
  
  if (cell == nil) {
    cell = [[[LRSlidingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
  }
  
  ...
  
  return cell;
}

In order for the cell to be useful, you need to add your foreground content to the cell's contentView, like you would with a normal cell (or you can use the built-in text labels) and provide a custom background view for the cell by assigning it to the cell's backgroundView:

cell.textLabel.text = @"My sliding cell";
cell.backgroundView = [[[MyCustomView alloc] init] autorelease];

When the user swipes over a cell (from left to right), the content view will slide off-screen to reveal the background view. The cell can be reset by manually calling slideInContentView on the cell.

To complete the user experience, you should slide the content view back in to view when the user swipes on a different cell, or starts scrolling. LRSlidingTableViewCell doesn't do this automatically but this can be achieved easily using a few delegate hooks. To see how this is done, check out this example controller.