2014年4月13日日曜日

UITableViewControllerの基本形

#import "TableViewController.h"

@interface XXXViewController ()
@property (strong, nonatomic) NSArray *datas;   // UITableViewに表示するデータ
@end

@implementation XXXViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // UITableViewに表示するデータ
    _datas =  @[@"January", @"February", @"March", @"April", @"May",
                @"June", @"July", @"August", @"September", @"October",
                @"November", @"December" ];
}

#pragma mark - Table view data source

// TableView内のセクション数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// セクション内の行数(=セル数)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datas.count;
}

// 表示セルの生成(表示内容設定)
// TableViewは、テーブルの行を表示する必要が生じるたびにこのメソッドを呼び出す
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Storyboardで設定したセルのIdentifier
    static NSString *CellIdentifier = @"Cell";
    // セルの生成
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // セルの表示内容設定
    cell.textLabel.text = [_datas objectAtIndex:indexPath.row];
    
    return cell;
}

#pragma mark - Table view delegate

// セルがタップされた時
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // セルの選択状態の解除
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //タップセル取得
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    //
    // タップ時の処理を記述
    //
}

@end

0 件のコメント:

コメントを投稿