iOS tableViewパーティション+インデックス

2561 ワード

1.新しいFile->Cocoa Touch->Objective-C class->Class:ViewControl,Subclass of:UIViewControlを作成する
2.xibを開き、viewにTable Viewを追加し、Table Viewの2つのプロパティをFile's Ownerにドラッグします.
tableviewのパーティションスタイルを設定してstyleを選択できます
3.ViewController.h:
#import 
@interface newViewController : UIViewController
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@property(retain,nonatomic)NSDictionary *dic;
@property(retain,nonatomic)NSArray *keys;
@end

4.ViewController.m:
#import "newViewController.h"

@interface newViewController ()

@end

@implementation newViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];
    self.dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    self.keys = [self.dic allKeys];
    self.keys = [self.keys sortedArrayUsingSelector:@selector(compare:)];
}

//tableView 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.keys count];
}

// 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = self.keys[section];// key
    NSArray *arr = [self.dic objectForKey:key];// key Array
    return [arr count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"str";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    int section = [indexPath section];
    int row = [indexPath row];
    
    NSString *key = self.keys[section];
    NSArray *arr = [self.dic objectForKey:key];
    cell.textLabel.text = arr[row];
    return cell;
}
// 
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.keys[section];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.keys;
}

@end