iOSアプリでテーブルビューを試してみる
iOSアプリでテーブルビューを試してみる。
【参考】 SwiftでのTableView データ表示編 - Qiita http://qiita.com/senseiswift/items/9b5476531a843b0e314a
次にViewControllerを修正して行く。
「UITableViewDataSource」「UITableViewDelegate」を追加。
class ViewController: UIViewController {
↓
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
表示する内容を定義しておく。
// 表示内容の一覧 let titles = ["aaa", "bbb", "ccc", "ddd", "eee"]
デリゲートとデータソースの設定を追加。(よく分かってないが、見よう見まねで追加)
override func viewDidLoad() { ・・・ // デリゲートとデータソースの設定 textView.delegate = self textView.dataSource = self }
以下の処理を追加。(これらもよく分かっていない)
// セルの行数を返す func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles.count } // セルの内容を返す func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") cell.textLabel?.text = titles[indexPath.row] return cell }
タップした場合の処理
下記の処理を追加し、タップした場合、アラートを表示させてみる。
// タップされた場合 func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { let msg = titles[indexPath.row] // アラートを表示 let alertController = UIAlertController(title: "tap", message: msg, preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) }