2017-01-02 10 views
1

alertViewControllerを使用してテキストを取得し、文字列の配列に追加して、新たに追加されたセルでtableViewを再ロードしようとしています。再読み込み後に書式設定に問題があるようです。UITableViewに新しい行を挿入しようとすると書式設定の問題が発生する

import UIKit 

class TableViewController: UITableViewController, UINavigationControllerDelegate { 
    // store the tasks in an array of strings 
    var tasks = [String]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.title = "Task List" 
     self.navigationItem.rightBarButtonItem = self.editButtonItem 
     self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addRow)) 
    } 

    func addRow() { 
     let ac = UIAlertController(title: "Add a task to the list", message: nil, preferredStyle: .alert) 

     // add a text field 
     ac.addTextField { 
      (textField) -> Void in 
      textField.placeholder = "" 
     } 

     // add "cancel" and "ok" actions 
     ac.addAction(UIAlertAction(title: "Cancel", style: .cancel)) 
     let createNewRow = UIAlertAction(title: "OK", style: .default) { action -> Void in 
      let text = ac.textFields?.first?.text 
      self.tasks.append(text!) 
      self.loadView() 
     } 
     ac.addAction(createNewRow) 

     present(ac, animated: true, completion: nil) 

    } 
    // MARK: - Table view data source 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return tasks.count 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Task", for: indexPath) 

     cell.textLabel?.text = tasks[indexPath.row] 

     return cell 
    } 

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      tasks.remove(at: indexPath.row) 
      tableView.deleteRows(at: [indexPath], with: .fade) 
     } else if editingStyle == .insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
     }  
    } 
} 

答えて

1

あなたの問題はあなたがself.loadViewを(呼び出した)の代わりに、アラートビューコントローラのアクションでself.tableView.reloadData()の:Appleのドキュメントから

let createNewRow = UIAlertAction(title: "OK", style: .default) { action -> Void in 
     let text = ac.textFields?.first?.text 
     self.tasks.append(text!) 
     self.tableView.reloadData() // self.loadView() is wrong. 
    } 
    ac.addAction(createNewRow) 

https://developer.apple.com/reference/uikit/uiviewcontroller/1621454-loadview

このメソッドを直接呼び出してはいけません。ビューコントローラは、ビュープロパティが要求されていて現在はnilであるときに このメソッドを呼び出します。 このメソッドはビューをロードまたは作成し、それをビュー プロパティに割り当てます。

関連する問題