Table Viewの使い方
2011年3月11日:iOS
Table Viewはテキストなどを行で表示することのできるViewです。行の中から好きなモノを選択することができます。ここではこのTable Viewの使い方について解説します。
プロジェクトの作成
プロジェクトを作成します。Xcodeを開き「Create a new Xcode project」を選択します。
そして、iOSのSingle View Applicationを選択します。
最後にプロジェクト名と言語を選びプロジェクトを作成します。ここでは言語としてSwiftを使用します。
Table Viewを設置する
Table ViewとTable View Cellの設置
Main.storyboardへ移動して、Table ViewをObjectライブラリから設置します。設置したら画面いっぱいに貼れるようにサイズを調整します。
さらに、Table View CellをTable Viewへ設置します。
続いて、Cellを選択したまま、AtributesインスペクタにおけるStyleをSubtitleとします。これにより、Cellにはタイトルとサブタイトルが表示されるようになります。そして、Identifierを「Cell」とします。
データソースとデリゲートの指定
テーブルに表示するデータの元を指定する必要があります。そのためにTable Viewをcontrolを押しながらクリックします。すると、以下のような画面がでるので、dataSourceとdelegateをView Controllerへドラッグ&ドロップでつなげます。
その後に、ViewControllerクラスの末尾に「UITableViewDelegate, UITableViewDataSource」を追加します。
class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource{
これによりTableViewをViewController内で扱えるようになります。
UITableViewDataSourceの設定
以上の用にUITableViewDataSourceを加えると、ViewControllerへ必要な記載がないためにエラーがでます。そこで、必要な項目をコーディングしていきます。ただ、何が必要なのかわからないので、UITableViewDataSourceをCommandキーを押しながらクリックします。
すると、UITableViewDataSourceのプロトコル定義へ移動します。以下のように表示されます。
protocol UITableViewDataSource : NSObjectProtocol { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell optional func numberOfSectionsInTableView(tableView: UITableView) -> Int // Default is 1 if not implemented optional func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? // fixed font style. use custom view (UILabel) if you want something different optional func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? // Editing // Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable. optional func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool // Moving/reordering // Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath: optional func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool // Index optional func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! // return list of section titles to display in section index view (e.g. "ABCD...Z#") optional func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int // tell table which section corresponds to section title/index (e.g. "B",1)) // Data manipulation - insert and delete support // After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change // Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead optional func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) // Data manipulation - reorder / moving support optional func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) }
ここで、optionalがついていない項目は必ずコーディングしないといけません。そこでコピ&ペーストでソースへもってきます。今回は、上の4つの関数を使用するので移動します。すると以下のようになります。
class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ } func numberOfSectionsInTableView(tableView: UITableView) -> Int { } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
セクションの数と行の設定
Tableにはセクションという値があります。例えば、
セクション1
- 行
- 行
- 行
- 行
セクション2
- 行
- 行
といったかんじです。このセクション数はnumberOfSectionsInTableViewの戻り値で設定します。ここでは、セクション数を2とするので
func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2; }
となります。指定がなければセクション数は1となります。
次にセクションにおける行数を設定します。その設定のために
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ if section==0{ return 4 }else{ return 2 } }
とします。これは必須の項目となります。ここでは一番初めのセクションの行数を4として、他は2つとしています。
セクションのタイトル
セクションのタイトルは以下のように設定します。
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "セクション"+section.description }
ここでは「セクション+番号」という感じで表示させるようにしています。
セルのタイトルとサブタイトル
セルに表示させるタイトルとサブタイトルを以下のようにして設定します。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell=tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath:indexPath) as UITableViewCell cell.textLabel?.text="セルのタイトル"+(indexPath.row).description cell.detailTextLabel?.text="セルのサブタイトル" return cell }
ここではタイトルに「セルのタイトル+行番号」、サブタイトルに「セルのサブタイトル」と表示させています。
UITableViewDelegateの設定
同様にしてdelegateの設定も行います。UITableViewDelegateでは、行が選択された際の処理を記述することができます。DataSourceと同様に⌘+クリックでプロトコルの確認ができます。一つ必須項目があるので、以下のように関数を追加します。
func tableView(tableView:UITableView,didSelectRowAtIndexPath indexPath:NSIndexPath){ println("セクション\(indexPath.section),セル\(indexPath.row)") }
この部分が行が押されたときの処理になります。行を選択すると「セクション番号、セル番号」が表示されます。
実行結果
プログラムを実行すると、以下のような画面が表示されます。そして、セルを押すと、セクション番号とセル番号が表示されます。
著者:安井 真人(やすい まさと)
@yasui_masatoさんをフォロー