UITableViewをStoryboard上でStatic Cellsみたいに使ってみる

Static Cellsはコード量が極端に減り非常に有効ですが、UITableViewController上でしか使えない制限があるためカスタマイズしにくい欠点があります。UIViewControllerにUITableViewを載せてできるだけStoryboard上で定義する方法を紹介しました。


UIViewController継承のControllerにUITableViewのdelagate, dataSourceを定義する


TableViewのContentプロパティは通常通りDynamic Propertiesにする
Prototype cellsはStoryboard上で扱うCell数


TableViewCellのidentifierを"cell_0_0", "cell_0_1"のように"cell_{sectionNo}_{rowNo}"にする


UITableViewを載せたControllerのUITableViewDataSourceをオーバーライドする

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //prototype cellsで設定した数
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView dequeueReusableCellWithIdentifier:
            [NSString stringWithFormat:@"cell_%d_%d", indexPath.section, indexPath.row]
            ];
}


あくまで通常のUITableViewの機構に頼っただけのものなので、高さの変更など必要があればそれぞれのDelegateメソッドをオーバーライドする必要があります。

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
     [NSString stringWithFormat:@"cell_%d_%d", indexPath.section, indexPath.row]
     ];
    return cell.frame.size.height;
}

Dynamic propertiesは通常のUITableView通りに、Section, Rowをコードで制御する仕組みであるため、Storyboardのパレット上にTableSectionを扱うパーツが存在しません。残念ながらヘッダー、フッターの制御はコードで定義するか、Cellのパーツを拡張してUser Defined Runtime Attributesを利用するなどの工夫が必要になります。そこまでStoryboard上の編集にこだわるメリットは薄いとは思いますが。今後、Static Cellsが進化して使いやすくなることを願います。

サンプルプロジェクト

https://github.com/hmori/StoryboardTest


参考サイト

UITableViewのStatic Cellsが使えなかったけどstoryboardでできる限りそれっぽくやってみた



Storyboardは個人的に今後の進化に非常に期待がもてる内容だと思います。iOS開発はデザイナ・プログラマなどと複数人での分業が難しいと感じていましたが可能性があるように見えますね。色々と工夫すればデータ部、コントロール部、デザイン部が効果的に分離できるか、これからも調べていきたいと思います。