Skip to main content

Expanding/Collapsing TableView Sections - iOS

I could not figure out a way to get this functionality as class extension, which would have been nice. But this is not possible if you need an instance variable to keep track of something. The finished subclass will look and behave just like the original Twitter app for iPhone does.
We start out by creating a new UITableView subclass which has a NSMutableSet instance variable to contain the section numbers which are already expanded. Don’t let yourself be daunted by the sheer amount of code. That’s really much ado about nothing.
UITableViewControllerWithExpandoSections.h
@interface UITableViewControllerWithExpandoSections : UITableViewController 
{
    NSMutableIndexSet *expandedSections;
}
NSIndexSet and the mutable cousin NSMutableIndexSet allow you to store an index, i.e. a number. It has methods to add such a number, remove it and query if it is contained in it. Being a set means that it is not ordered and each entry is automatically unique.
Here’s the code, please go through it and see if you can figure out what’s happening.
UITableViewControllerWithExpandoSections.m
#import "UITableViewControllerWithExpandoSections.h"
#import "DTCustomColoredAccessory.h"
 
@implementation UITableViewControllerWithExpandoSections
 
- (void)dealloc
{
    [expandedSections release];
    [super dealloc];
}
 
- (void)viewDidLoad
{
    [super viewDidLoad];
 
    if (!expandedSections)
    {
        expandedSections = [[NSMutableIndexSet alloc] init];
    }
}
 
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
    if (section>0) return YES;
 
    return NO;
}
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self tableView:tableView canCollapseSection:section])
    {
        if ([expandedSections containsIndex:section])
        {
            return 5; // return rows when expanded
        }
 
        return 1; // only top row showing
    }
 
    // Return the number of rows in the section.
    return 1;
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
 
    // Configure the cell...
 
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // first row
            cell.textLabel.text = @"Expandable"; // only top row showing
 
            if ([expandedSections containsIndex:indexPath.section])
            {
                cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
            }
            else
            {
                cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
            }
        }
        else
        {
            // all other rows
            cell.textLabel.text = @"Some Detail";
            cell.accessoryView = nil;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    else
    {
        cell.accessoryView = nil;
        cell.textLabel.text = @"Normal Cell";
 
    }
 
    return cell;
}
This code introduces method tableView:canCollapseSection: that can make individual sections collapsible or not. In this example I make sections 1 and 2 such, section 0 cannot expand.
The mutable index set gets instantiated in viewDidLoad and released in dealloc. So far so good. Knowing what I told you above about index set you can easily see how this is used to determine whether a section should show as expanded or collapsed. If the index is in the set, then numberOfRowsInSection returns the full number of detail cells, otherwise 1 for the header. You can also see that I’m using a DTCustomColoredAccessory, more on that later.
The expansion and collapse animation is simply achieved by using the built-in tableview animations to insert and delete cells. Note that these are only animating, if you don’t make sure that numberOfRowsInSection returns the correct new number BEFORE invoking the animating method then you will get an exception. So: first make sure that the number is changed, then call the animation.
Here’s the code for that.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // only first row toggles exapand/collapse
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
            NSInteger section = indexPath.section;
            BOOL currentlyExpanded = [expandedSections containsIndex:section];
            NSInteger rows;
 
            NSMutableArray *tmpArray = [NSMutableArray array];
 
            if (currentlyExpanded)
            {
                rows = [self tableView:tableView numberOfRowsInSection:section];
                [expandedSections removeIndex:section];
 
            }
            else
            {
                [expandedSections addIndex:section];
                rows = [self tableView:tableView numberOfRowsInSection:section];
            }
 
            for (int i=1; i<rows; i++)
            {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                                                               inSection:section];
                [tmpArray addObject:tmpIndexPath];
            }
 
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
 
            if (currentlyExpanded)
            {
                [tableView deleteRowsAtIndexPaths:tmpArray 
                                 withRowAnimation:UITableViewRowAnimationTop];
 
                cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
 
            }
            else
            {
                [tableView insertRowsAtIndexPaths:tmpArray 
                                 withRowAnimation:UITableViewRowAnimationTop];
                cell.accessoryView =  [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
 
            }
        }
    }
}
In both cases I have to construct an array that contains the index paths of the rows 1 through 4, once for inserting, once for deleting. At the same time I’m grabbing the header cell so that I can update the accessory view with the appropriate arrow direction. Now, let me also give you the custom accessory view, which is based on my previous article on how to custom-draw a disclosure indicator I simply added a type enum and modifications in drawRect.
DTCustomColoredAccessory.h
typedef enum 
{
    DTCustomColoredAccessoryTypeRight = 0,
    DTCustomColoredAccessoryTypeUp,
    DTCustomColoredAccessoryTypeDown
} DTCustomColoredAccessoryType;
 
@interface DTCustomColoredAccessory : UIControl
{
 UIColor *_accessoryColor;
 UIColor *_highlightedColor;
 
    DTCustomColoredAccessoryType _type;
}
 
@property (nonatomic, retain) UIColor *accessoryColor;
@property (nonatomic, retain) UIColor *highlightedColor;
 
@property (nonatomic, assign)  DTCustomColoredAccessoryType type;
 
+ (DTCustomColoredAccessory *)accessoryWithColor:(UIColor *)color type:(DTCustomColoredAccessoryType)type;
 
@end
DTCustomColoredAccessory.m
#import "DTCustomColoredAccessory.h"
 
@implementation DTCustomColoredAccessory
 
- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
  self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
 
- (void)dealloc
{
 [_accessoryColor release];
 [_highlightedColor release];
    [super dealloc];
}
 
+ (DTCustomColoredAccessory *)accessoryWithColor:(UIColor *)color type:(DTCustomColoredAccessoryType)type
{
 DTCustomColoredAccessory *ret = [[[DTCustomColoredAccessory alloc] initWithFrame:CGRectMake(0, 0, 15.0, 15.0)] autorelease];
 ret.accessoryColor = color;
    ret.type = type;
 
 return ret;
}
 
- (void)drawRect:(CGRect)rect
{
    CGContextRef ctxt = UIGraphicsGetCurrentContext();
 
    const CGFloat R = 4.5;
 
    switch (_type) 
    {
        case DTCustomColoredAccessoryTypeRight:
        {
            // (x,y) is the tip of the arrow
            CGFloat x = CGRectGetMaxX(self.bounds)-3.0;;
            CGFloat y = CGRectGetMidY(self.bounds);
 
            CGContextMoveToPoint(ctxt, x-R, y-R);
            CGContextAddLineToPoint(ctxt, x, y);
            CGContextAddLineToPoint(ctxt, x-R, y+R);
 
            break;
        }    
 
        case DTCustomColoredAccessoryTypeUp:
        {
            // (x,y) is the tip of the arrow
            CGFloat x = CGRectGetMaxX(self.bounds)-7.0;;
            CGFloat y = CGRectGetMinY(self.bounds)+5.0;
 
            CGContextMoveToPoint(ctxt, x-R, y+R);
            CGContextAddLineToPoint(ctxt, x, y);
            CGContextAddLineToPoint(ctxt, x+R, y+R);
 
            break;
        } 
 
        case DTCustomColoredAccessoryTypeDown:
        {
            // (x,y) is the tip of the arrow
            CGFloat x = CGRectGetMaxX(self.bounds)-7.0;;
            CGFloat y = CGRectGetMaxY(self.bounds)-5.0;
 
            CGContextMoveToPoint(ctxt, x-R, y-R);
            CGContextAddLineToPoint(ctxt, x, y);
            CGContextAddLineToPoint(ctxt, x+R, y-R);
 
            break;
        } 
 
        default:
            break;
    }
 
    CGContextSetLineCap(ctxt, kCGLineCapSquare);
    CGContextSetLineJoin(ctxt, kCGLineJoinMiter);
    CGContextSetLineWidth(ctxt, 3);
 
 if (self.highlighted)
 {
  [self.highlightedColor setStroke];
 }
 else
 {
  [self.accessoryColor setStroke];
 }
 
 CGContextStrokePath(ctxt);
}
 
- (void)setHighlighted:(BOOL)highlighted
{
 [super setHighlighted:highlighted];
 
 [self setNeedsDisplay];
}
 
- (UIColor *)accessoryColor
{
 if (!_accessoryColor)
 {
  return [UIColor blackColor];
 }
 
 return _accessoryColor;
}
 
- (UIColor *)highlightedColor
{
 if (!_highlightedColor)
 {
  return [UIColor whiteColor];
 }
 
 return _highlightedColor;
}
 
@synthesize accessoryColor = _accessoryColor;
@synthesize highlightedColor = _highlightedColor;
@synthesize type = _type;
 
@end
This is technically a quite simple exercise, but still a ton of code is required to achieve the desired effect. What have we learned? NSIndexSet is a comfortable way to store indexes. We get a cool animation by using the insertion and deletion methods of UITableView, provided we change the number of rows method’s result in advance of invoking the animation methods. And finally we can go the extra mile and create a custom accessory view that also reacts appropriately to being highlighted.

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

Video Calling In IOS Objective C

Video Calling Sources Project homepage on GIT — https://github.com/QuickBlox/quickblox-ios-sdk/tree/master/sample-videochat-webrtc Download ZIP - https://github.com/QuickBlox/quickblox-ios-sdk/archive/master.zip Overview The VideoChat code sample allows you to easily add video calling and audio calling features into your iOS app. Enable a video call function similar to FaceTime or Skype using this code sample as a basis. It is built on the top of WebRTC technology.            System requirements The QuickbloxWebRTC.framework supports the next:     * Quickblox.framework v2.7 (pod QuickBlox)     * iPhone 4S+.     * iPad 2+.     * iPod Touch 5+.     * iOS 8+.     * iOS simulator 32/64 bit (audio might not work on simulators).     * Wi-Fi and 4G/LTE connections. Getting Started with Video Calling API Installation with CocoaPods CocoaPods is a dependency manag...