Skip to content
This repository has been archived by the owner on Jun 20, 2023. It is now read-only.

4.1 uitableviewについて

yuichi takeda edited this page Mar 19, 2015 · 11 revisions

公式ドキュメントはこちらをご覧ください

https://developer.apple.com/jp/devcenter/ios/library/documentation/TableView_iPhone.pdf

UITableViewとは

TableViewとはiOSのアプリケーションで良く用いられる、垂直方向にスクロールしながら情報を表示することの出来るUIViewのサブクラスの一つです。

https://raw.github.com/mixi-inc/iOSTraining/master/Doc/Images/4.1/tableview_example.png

iOS Table Viewプログラ ミングガイドより引用

特徴

  • スクロールは垂直方向にのみ行うことができる
    • (補足:iOS6から垂直と水平の両方にセルを置くことの出来るUICollectionViewが登場しました)
  • 表示するコンテンツはセルとよばれる単位ごとに構成し、セクションで区切ることもできる
  • delegateやdatasourceなどのプロトコルを実装することで、表示するデータなどを制御する

どういう時に使うのか

Appleのドキュメントによると、以下のような目的で利用することを想定しています。

  • 階層構造のデータ内をユーザが移動できるようにする
  • インデックス付きの項目リストを表示する
  • 視覚的にグループ分けされた詳細情報とコントロールを表示する
  • 選択可能な選択肢リストを表示する

様々なシーンで用いられます。mixi公式クライアントアプリだと、

  • ホーム画面(フィード一覧)
  • ホーム詳細
  • 設定画面、通知画面、友人一覧... etc

https://raw.github.com/mixi-inc/iOSTraining/master/Doc/Images/4.1/tableview_of_mixi.png

と多岐にわたり、様々な箇所で使われます。

UITableViewの構造

  • datasourceとdelegateの二つのプロトコルを持つ
    • datasource : 各行やセクションに埋めるデータを供給する役割を持つ
    • deleagte : viewの外観やセルが選択された時にとるアクションを定義する
  • 各行はセルを用いて描画を行う
  • 各行ごとに選択された時に何かしら動作を行う

実習

このUITableViewを実際に表示しながら、TableViewの仕組みに慣れて行きましょう

サンプルプロジェクトの作成

  • Xcodeからサンプルプロジェクトを開き、新しいプロジェクトでSingleViewApplicationを選びます。 https://raw.github.com/mixi-inc/iOSTraining/master/Doc/Images/4.1/link_xib_and_mfile.png
  • view controller のxibを選び、viewにTableViewをドロップします。(変数名はtableViewとしました) https://raw.github.com/mixi-inc/iOSTraining/master/Doc/Images/4.1/put_tableview_on_view.png
  • xibのtableviewと実装ファイル(.m)とを結びます。(.hファイルでも構いません)
  • ヘッダファイルで、UITableViewDataSourceとUITableViewDelegateの継承を宣言します。
@interface TVSViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
  • tableViewのdataSourceとdelegateをselfにセットします
_tableView.dataSource = self;
_tableView.delegate = self;

こうすることで、tableviewのデータの源(何個セルを表示するか、セルに何を表示するか)としての働きと、見た目(各セルの高さやセルが選択されたときのアクション)などの処理が委譲されたことになります。

tableviewのdataSource, delegateメソッドの追加

UITableViewのDataSourceやDelegateには主に以下のメソッドがあります

UITableViewDataSource

  • - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    • section目のセクションにいくつ行があるかを返す
  • - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    • indexPathの位置にあるセルを返す
  • - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    • tableViewにいくつセクションがあるか。明記しない場合は1つ
  • - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    • section目のセクションのタイトルを返す

UITableViewDelegate

  • - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    • indexPathの位置にあるセルの高さを指定
  • - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    • indexPathの位置にあるセルが選択された時に呼ばれる
  • - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    • section目のセクションのヘッダービューを作って返す

※indexPathとは

  • 第hoge章、第fuga段落、第piyo項目のような階層構造のindexを指定できるオブジェクト
  • よく使うのは indexPath.section と indexPath.row

※ DataSourceとDelegateの詳細はこちらをどうぞ

この中で、@requiredなメソッドであるtableView:cellForRowAtIndexPath:とtableView:numberOfRowsInSection:を実装します。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        [tableView registerClass:[UITableView class] forCellReuseIdentifier:@"Cell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row]; // 何番目のセルかを表示させました
    return cell;
}

dequeueReusableCellWithIdentifierについて UITableViewでは、同じタイプのセルを使い回すことがよくあるため、内部でそのセルをキャッシュしておく仕組みがあります。一度表示したけど非表示になったセルなどがこのキャッシュに回されてdequeueReusableCellWithIdentifierを使うことでキャッシュされたセルを再利用して表示します。 利用するセルはtableViewに予め登録しておく必要があります。登録には tableView registerClass:forCellReuseIdentifier: のメソッドを利用します。registerClassには利用するセルのクラスを、CellReuseIdentifierにはキャッシュから引いてくるときに利用する識別子を指定します。 登録は、セルを利用するときでも構いませんし、viewDidLoadなどの初期化のときにしておいても構いません。

ここまでを実行して、このような画面が出て来れば成功です。

https://raw.github.com/mixi-inc/iOSTraining/master/Doc/Images/4.1/result.png

時間があれば

  1. セルの再利用 - 行の数を100個ほどにtableView:cellForRowAtIndexPath:を以下のように書き換えてみてください。 途中から番号がおかしいものがちらほら出てくると思います。これは、セルを再利用した結果以前書き込んだ内容が消去されていないために起きます。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row]; // 移動させた
    }

    return cell;
}
  1. tableviewのスタイルを変える - UITableViewにはPlain, Groupdの二種類のスタイルが用意されています。デフォルトではPlainが設定されていますが、xib上から変更することも可能です。 Attribute Inspector から Table View のスタイルを変更してみたください。

はじめに

  1. iOSについて

  2. Xcode最初のステッフ

  3. 導入

  4. Objective C の基礎

  5. メモリ管理

  6. 1.3 UIViewController1 UIViewController のカスタマイズ(xib, autoresizing)

  7. 1.3 UIViewController1 UIViewController のカスタマイズ(storyboard)

  8. UIViewController2 - ModalViewController

  9. UIViewController2 - ModalViewController(storyboard)

  10. UIViewController3 - ライフサイクル

  11. HomeWork 1 Objective C の基本文法

  12. HomeWork 2 UIViewControllerとModalViewController

  13. HomeWork 3 UIViewController + Animation

  14. UIKit 1 - container, rotate-

  15. UINavigationController

  16. UITabController

  17. Custom Container View Controller

  18. Supporting Multiple Interface Orientations

  19. HomeWork 1 - タブバーからモーダルビューを表示する

  20. HomeWork 2 - NavigationController

  21. HomeWork 2.3 デバイスことに回転対応

  22. UIKit 2- UIView -

  23. UIView

  24. UIView のカスタマイズ

  25. UIView Animation

  26. HomeWork 1 - UIScrollView

  27. UIKit 3 - table view -

  28. UITableView について

  29. UITableViewとNavigationController

  30. custom UITableViewCell の作成

  31. UITableViewのその他のオプション、カスタマイズ

  32. HomeWork 1 - Dynamic height with a custom uitableviewcell

  33. UIKit 4 - image and text -

  34. UIImagePickerController

  35. Assets Library

  36. UITextFiled, UITextView

  37. KeyboardNotification

  38. Homework 1 - フォトの複数枚選択

  39. ネットワーク処理

  40. NSURLConnection

  41. JSONのシリアライズとデシリアライズ

  42. UIWebView

  43. ローカルキャッシュと通知

  44. NSUserDefaults, Settings Bundle

  45. NSFileManager

  46. Key Value Observing

  47. NSNotification、NSNotificationCenter を用いた通知

  48. UILocalNotification

  49. Blocks, GCD

  50. Blocks

  51. GCD

  52. 【演習】GCD,-Blocksを用いたHTTPリクエストマネージャの作成

  53. 設計とデザインパターン

  54. クラス設計 1

  55. クラス設計 2

  56. [クラス設計演習] (https://github.com/mixi-inc/iOSTraining/wiki/9.3-%E3%82%AF%E3%83%A9%E3%82%B9%E8%A8%AD%E8%A8%88%E6%BC%94%E7%BF%92)

  57. 開発ツール

  58. Instruments, デバッガ

  59. CocoaPods

  60. テスト

  61. iOS開発におけるテスト

  62. GHUnit

  63. Kiwi

  64. KIF

  65. In-App Purchase

  66. In-App Purchase

  67. 付録

  68. Tips of Xcode

  69. Auto Layout 入門

  70. Auto Layout ドリル

Edit sidebar

Clone this wiki locally