SwiftによるiPhoneアプリ開発入門(超初歩)その8 -複数セクション(グループ分け)したリスト-
前回はセクションを分けない(グループ分けしない)でリストを一括表示しましたが、今回はリストをセクションに分けてみます。
1、リスト上に表示させる画像をSupporting Filesディレクトリへ配置
2、ストーリーボードから既存のシーンを削除し、Table View Controllerをl配置して初期画面に設定
3、セルのプロパティを編集し、セルのスタイルとidentifierを設定
4、ドキュメントアウトラインから、Table View を選択し、右の設定画面でStyleをGroupedに設定
5、既存ビューコントローラを削除し、UITableViewControllerのサブクラスを作成して実装
6、セクションのヘッダに表示するデータとテーブルに表示するデータを実装
let sectionHeaderTexts = ["女性向け商品", "男性向け商品"] var items: [[(text: String, detail: String, fileName: String)]] = [ [ ("メガネ", "知的な印象を与えます", "glasses1.jpeg"), ("帽子", "日差しを避けて涼しさを。", "hat1.jpeg"), ("ドレス", "街中で視線を集めます", "suit1.jpeg"), ("シューズ", "歩きやすさを重視", "shoes1.jpeg"), ], [ ("メガネ", "個性が光ります", "glasses2.jpeg"), ("帽子", "夏にぴったりです。", "hat2.jpeg"), ("ドレス", "機能性が非常に高いです。", "suit2.jpeg"), ("シューズ", "山歩きにどうぞ", "shoes2.jpeg"), ] ]
7、セクションの設定を実装
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // 作成するセクションの数を返す return sectionHeaderTexts.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // セクション毎の行数を返す return items[section].count } // セクションのヘッダー文字列を返す override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionHeaderTexts[section] }
8、セクションを作成して返す
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 再利用できるセルがあれば取得する // 第一引数には、ストーリーボードで設定したセルのidentifierを指定 let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell // セクション番号 let section = indexPath.section // セクション内での番号 let rowInSection = indexPath.row // 表示するUIImageのファイル名 let fileName = items[section][rowInSection].fileName // セルの内容を設定 cell.textLabel?.text = items[section][rowInSection].text cell.detailTextLabel?.text = items[section][rowInSection].detail cell.imageView?.image = UIImage(named: fileName) return cell }
9、作成したTableViewControlをストーリーボード上のシーンと対応付け