2014年4月13日日曜日

UITableViewのカスタムセルをxibで作成する


カスタムセルをxibで作成する。
1)XcodeでNew File…->Cocoa TouchのObjective-C classを選択してNext->UITableViewCellのサブクラスとしてClassを入力してNext->Create
2)XcodeでNew File…->User InterfaceのViewを選択してNext->Device Familyを選択してNext->xibの名称を入力してCreate
3)xibからViewを削除
4)xibにTable View Cellをドロップ
5)xibのClassを1)で作成したクラスにする
6)xibのReuse Identifierを入力
7)xibで幅・高さ設定
8)xibにlabelやimageView等のパーツを配置して、カスタムセルクラスにアウトレット

ViewControllerでtableViewの registerNib: forCellReuseIdentifier: でカスタムセルをレジスターして、
dequeueReusableCellWithIdentifier:forIndexPath: でカスタムセルを生成する。

#import "XXXViewController.h"
#import "CustomCell.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" ];
    
    // tableViewにcustomCellのクラスを登録
    UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"CustomCell"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 登録したカスタムセルの取得
    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.label.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 件のコメント:

コメントを投稿