xyk blog

最近は iOS 開発の記事が多めです。

UIViewController で UITableView を実装する

環境:iOS Deployment Target 7.1

UITableViewController を使わず、UIViewController で UITableView を実装する方法について。

  • ヘッダファイルに UITableViewDelegate、UITableViewDataSource プロトコルを追加
  • UITableView オブジェクトを作成してdelegatedataSource先に ViewController を設定
  • セルクラスを登録
  • tableView:numberOfRowsInSection:tableView:cellForRowAtIndexPath:の実装

ExampleViewController.h

#import <UIKit/UIKit.h>

@interface ExampleViewController : UIViewController
<
UITableViewDelegate,
UITableViewDataSource
>
@end

ExampleViewController.m

#import "ExampleViewController.h"

@interface ExampleViewController ()

@end

@implementation ExampleViewController
{
    UITableView *_tableView;
    NSArray *_items;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _tableView = [[UITableView alloc] initWithFrame:[self.view bounds]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

    // テストデータ追加
    _items = @[@"item 1", @"item 2", @"item 3", @"item 4", @"item 5"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = _items[indexPath.row];
    return cell;
}

@end