UITextField の入力内容を UITableView で表示するアプリ 2 / 100 [Swift iPhoneアプリ 100本ノック]
こんばんは!
id:yukihiro1010 です.
今日は,多くのアプリで使用されている UITableView を使ったアプリを開発しました!
このアプリは,UITextField の入力内容を UITableView で表示するシンプルなものです.
今回のソースコードでやっていることは以下の通りです.
- 構造体(名前,説明を含む)を定義
- UITableView の実装
- 名前と説明を入力するための UITextField を定義して,入力内容を取得
- その内容をテーブルに追加して表示
- テーブルのセルを編集可能にし,削除できるようにした
- テーブルの1番下から削除していくボタンを設置
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var titleField: UITextField! @IBOutlet weak var desField: UITextField! @IBOutlet weak var itemTable: UITableView! struct Item { var name: String = "no-name" var desc: String = "no-desc" } var items: [Item] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. itemTable.delegate = self itemTable.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addButton() { items.append(Item(name: titleField.text, desc: desField.text)) titleField.text = "" desField.text = "" itemTable.reloadData() } @IBAction func removeButton() { items.removeLast() itemTable.reloadData() } /* 行数を返す関数(必須) */ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } /* 行ごとのセルの中身を設定する関数(必須) */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle , reuseIdentifier: nil) cell.textLabel?.text = items[indexPath.row].name cell.detailTextLabel?.text = items[indexPath.row].desc return cell } /* 編集可能/不可能を指定する関数 */ func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } /* 移動可能/不可能を指定する関数 */ func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } /* 指定した編集操作後の処理を記述する関数 */ func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { items.removeAtIndex(indexPath.row) itemTable.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } }