Is there a way to auto group/auto-section my UITableView
alphabetically? I have a huge array which is being displayed nicely, but it would be even better if I h
i did the following:
AutoSectionTableViewDataSource.h
@protocol AutoSectionTableViewDataSource
- (NSString*)tableView:(UITableView*)tableView sectionNameAtIndexPath:(NSIndexPath*)indexPath;
@end
@interface AutoSectionTableViewDataSource : NSObject
- (id)initWithDataSource:(NSObject*)dataSource;
@end
AutoSectionTableViewDataSource.m
@interface AutoSectionTableViewDataSource ()
@property(weak) NSObject *dataSource;
@end
@implementation AutoSectionTableViewDataSource
- (id)initWithDataSource:(NSObject*)dataSource
{
self = [super init];
self.dataSource = dataSource;
return self;
}
- (BOOL)respondsToSelector:(SEL)selector
{
if ([super respondsToSelector:selector]) return YES;
if (self.dataSource && [self.dataSource respondsToSelector:selector]) return YES;
return NO;
}
- (void)forwardInvocation:(NSInvocation*)invocation
{
if (self.dataSource && [self.dataSource respondsToSelector:invocation.selector]) {
[invocation invokeWithTarget:self.dataSource];
} else {
[self doesNotRecognizeSelector:invocation.selector];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
if (self.dataSource) return [self.dataSource methodSignatureForSelector:selector];
return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger rows = [self.dataSource tableView:tableView numberOfRowsInSection:0];
NSMutableSet *set = [[NSMutableSet alloc] init];
for (NSInteger row=0; row %@", section, sectionName);
return sectionName;
}
}
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger rows = [self.dataSource tableView:tableView numberOfRowsInSection:0];
NSMutableDictionary *tmp = [[NSMutableDictionary alloc] init];
NSInteger count = 0;
for (NSInteger row=0; row
and then in your code:
- (NSString*)tableView:(UITableView *)tableView sectionNameAtIndexPath:(NSIndexPath *)indexPath
{
return @"this would be your section name for indexPath.row"
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return total_number_of_rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return cell_for_indexPath.row;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// instead of self.tableView.dataSource = self; use:
self.autoSectionDataSource = [[AutoSectionTableViewDataSource alloc] initWithDataSource:self];
self.tableView.dataSource = self.autoSectionDataSource;
}