Objective-CでのUITableViewの作り方

iPhoneといえばTableViewですよね。


そして、TableViewを作ることすら出来なくてObjective-CによるiPhoneアプリ開発を挫折してTitaniumやることにしたという話を時々聞くので作り方の紹介です。
(まぁシンプルなTableViewベースのアプリケーションであればTitaniumでやった方が簡単に作れていいかなぁとは思います)

  • まずはわかりやすいようにViewBaseで作ります。
    • ほとんどの場合はNavigationBaseで作ることになると思うのですが、今回はシンプルな構造でわかりやすくするためにViewBaseで

f:id:koba04:20120304003815p:plain

  • とりあえずTableViewを貼り付けます。

f:id:koba04:20120304004312p:plain

  • TableViewを接続します

f:id:koba04:20120304004729p:plain

  • DataSourceとDelegateを設定します。
    • DataSourceはデータに対する要求を処理してくれるクラスで、DelegateはTableViewに対してのイベントを処理してくれるクラスを指定するもので、ここでは同じViewControllerにしています。

f:id:koba04:20120304004829p:plain

  • ここまでくれば後は少しコード書くだけです。
  • まずは.hにデータとして使う配列やdelegateを指定します。
@interface TableViewSampleViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
    
    UITableView *sampleTable;
    NSArray *tableData;
}
  • .mにデータとして使う配列にデータを入れます。
- (void)dealloc
{
    [sampleTable release];
    [tableData release];
    [super dealloc];
}
:
- (void)viewDidLoad
{
    [super viewDidLoad];
    tableData = [[NSArray alloc]initWithObjects:@"新宿", @"代々木", @"原宿", @"渋谷", nil];
    
}
  • UITableViewDataSourceのdelegateでrequiredになっているメソッドを実装します。
// 指定したindexのcellを作成する。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // セルを再利用するためのコード
    static NSString *cellID = @"SampleView";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:cellID]autorelease];
    }

    // ただ配列の値を設定しているだけ
    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
    return cell;
}


// データの総件数を返すメソッド
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableData count];
}
  • とりあえずこれだけ指定すればこんな感じでTableViewを使うことが出来ます。

f:id:koba04:20120304012419p:plain

  • あとはcellをクリックしたのイベントを追加したければ下記のメソッドを実装すれば出来ます。
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath


簡単ですね!


ソースはgistにあげておきました。
https://gist.github.com/1966940