環境
Xcode Version 10.1
Apple Swift version 4.2.1
不明点
シュミレーターで文字を「+」をタップ後、アラートが出てきた後
文字を打ってOKを押すと下記箇所がエラーで返されます。
[エラー箇所]
P.248の❻で行が追加されたことをテーブルに通知部分
[エラー文]
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
(和訳:Optional値の展開中に予期せずにnilが見つかりました)
swift
1// テーブルに行が追加されたことをテーブルに通知 2self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)],with:UITableView.RowAnimation.right)
参考書籍
コード全文
swift
1import UIKit 2 3class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { 4 // ToDoを格納した配列 5 var todoList = [String]() 6 7 @IBOutlet weak var tableView: UITableView! 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 } 12 13 // +ボタンをタップした時に呼ばれる処理 14 @IBAction func tapAddButton(_ sender: Any) { 15 // アラートダイアログの生成 16 let alertController = UIAlertController(title: "ToDo追加",message: "ToDoを入力してください",preferredStyle: UIAlertController.Style.alert) 17 // テキストエリアを追加 18 alertController.addTextField(configurationHandler: nil) 19 // OKボタンを追加 20 let okAction = UIAlertAction(title: "OK",style: UIAlertAction.Style.default) { (action: UIAlertAction) in 21 // OKボタンがタップされた時の処理 22 if let textField = alertController.textFields?.first { 23 // ToDoの配列に入力値を挿入。先頭に挿入する 24 self.todoList.insert(textField.text!, at: 0) 25 26 // テーブルに行が追加されたことをテーブルに通知 27 self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)],with: UITableView.RowAnimation.right) 28 } 29 } 30 // OKボタンがタップされた時の処理 31 alertController.addAction(okAction) 32 // CANCELボタンがタップされた時の処理 33 let cancelButton = UIAlertAction(title: "CANCEL",style: UIAlertAction.Style.cancel, handler: nil) 34 // CANCELボタンを追加 35 alertController.addAction(cancelButton) 36 37 // アラートダイアログを表示 38 present(alertController, animated: true, completion: nil) 39 } 40 41 // テーブルの行数を返却する 42 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 43 // Todoの配列の長さを返却する 44 return todoList.count 45 } 46 47 // テーブルの行ごとのセルを返却する 48 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 49 // Storyboardで指定したtodoCell識別子を利用して再利用可能なセルを取得する 50 let cell = tableView.dequeueReusableCell(withIdentifier: "todoCell", for: indexPath) 51 // 行番号に合ったToDoのタイトルを取得 52 let todoTitle = todoList[indexPath.row] 53 // セルのラベルにToDoのタイトルをセット 54 cell.textLabel?.text = todoTitle 55 return cell 56 } 57 58 59}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。