TableViewでセルを自分で作る(カスタムセル)苦闘メモ

「Table View custome cell」等で検索すると色々でてくる。公式ドキュメントはhttp://developer.apple.com/jp/devcenter/ios/library/documentation/TableView_iPhone.pdf:iOS Table Viewプログラミングガイト(PDF) なのだが、みんな同じことをいってるのかしら? 状態でよくわからない。

 やりかたは大きくわけて「コードで書く(xibをつかわない)」と「xibをつかう」があるのだが、コードで書くのはまだなれていないので、PDFの56ページあたりをお手本に、xibを使う場合のまとめ。

  • Master-Detail Application をもとにする
  • 空のxib「HogeView.xib」を作る
  • HogeView.xib:TableViewCellを配置する。そのなかにLabelなど必要なものを配置する。(今回はLabelを2つ作った)
  • HogeView.xib:File's OwnerのCustom Class(オーナー?)は MasterViewControllerにする
  • UITableViewCellのサブクラスで、HogeTableViewCell.m/.h を作る
  • HogeTableViewCell.h:HogeView.xibのTableViewCellのなかのLabelやButtonに対応するIBOutletなプロパティをつくる。
  • HogeView.xib:TableViewCellのCustom ClassをHogeTableViewCellに変える
  • HogeView.xib:HogeTableViewCell.hに定義したIBOutletなプロパティを、HogeView.xib内のそれぞれとくっつける
  • HogeView.xib:Identifierに何か名前「HogeCell」とかつける
  • MasterViewController.h:HogeTableViewCellのIBOutletなプロパティを作る。名前を tvCell とする。
  • HogeView.xib:File's Ownerを選択して右クリックででてくる tvCell を、TableViewCell(HogeTableViewCell)にくっつける
  • MasterViewController.h: cellForRowAtIndexPathメソッドでの、書き方が変わる。これはPDF通り。このとき、HogeView.xibで指定したIdentifierで指定した文字列「HogeCell」を使う。また、「HogeView.xib」を読み込むのもここ。
    static NSString *CellIdentifier = @"HogeCell";
    
    HogeTableViewCell *cell = (HogeTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"HogeView" owner:self options:nil];
        cell = tvCell;
        self.tvCell = nil;
    }

    cell.label1.text = [NSString stringWithFormat:@"ら%d",indexPath.row];
    cell.label2.text = [NSString stringWithFormat:@"り%d",NUMBER_OF_ROWS - indexPath.row];



 これがあっているのかこころもとない。
 コードだけで書いた方が楽そうだけど。
 
 
 まだまだ長い道のりのやうだ。