2015-11-06 2 views
0

Я пытаюсь изменить или удалить текст по умолчанию в tableview, я пробовал использовать следующий код, но как только пользователь перейдет на другой контроллер и обратно (или покинет приложение и вернется) текст возвращается к тексту по умолчанию. Как я могу заставить его работать? Я разместил весь код для tableView, чтобы вы могли просмотреть, что я мог сделать неправильно. спасибо!Как редактировать или удалять текст в таблицеView?

var places = [Dictionary<String,String>()] 

var activePlace = -1 

class TableViewController: UITableViewController { 

    func companyNameUpdatedAlert(title: String, error: String, indexPath: Int) { 

     let alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert) 

     alert.addTextFieldWithConfigurationHandler { (textField) -> Void in 

      textField.placeholder = "Enter new text" 

     } 

     alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in 

      let lat = places[indexPath]["lat"]! 

      let lon = places[indexPath]["lon"]! 

      places.removeAtIndex(indexPath) 

      places.insert(["name" : alert.textFields![0].text!, "lat" : lat, "lon" : lon], atIndex: indexPath) 

      self.tableView.reloadData() 


     })) 

     self.presentViewController(alert, animated: true, completion: nil) 


    } 

    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { 

     let changeText = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Change text" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in 

      self.companyNameUpdatedAlert("Update text", error: "enter text below", indexPath: indexPath.row) 

     }) 

     let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in 

      places.removeAtIndex(indexPath.row) 

      tableView.reloadData() 

     }) 

     return [changeText, deleteAction] 


    } 

    override func viewDidLoad() { 

     //save start 

     if NSUserDefaults.standardUserDefaults().objectForKey("places") != nil { 

      places = NSUserDefaults.standardUserDefaults().objectForKey("places") as! [Dictionary] 


      //save stop 

     super.viewDidLoad() 



     if places.count == 1 { 

      places.removeAtIndex(0) 

      places.append(["name":"Long press on map to add location","lat":"90","lon":"90"]) 



     } 
     if NSUserDefaults.standardUserDefaults().objectForKey("places") != nil { 

      places = NSUserDefaults.standardUserDefaults().objectForKey("places") as! [Dictionary] 


     } 

    } 
    } 

    override func didReceiveMemoryWarning() { 

     super.didReceiveMemoryWarning() 

    } 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

     return 1 

    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

     return places.count 


    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell 

     cell.textLabel?.text = places[indexPath.row]["name"] 

     return cell 



    } 

    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { 

     activePlace = indexPath.row 

     return indexPath 

    } 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

     if segue.identifier == "newPlace" { 

      activePlace = -1 


     } 

    } 

    override func viewWillAppear(animated: Bool) { 

     tableView.reloadData() 


    } 

} 

ответ

0

Когда вы редактируете таблицу, вы должны сохранять свои данные в NSUserDefaults. В противном случае вы просто меняете свойство класса, которое перезагружается с исходного NSUserDefaults каждый раз, когда загружается класс.

Попробуйте внутри UIAlertAction закрытия:

NSUserDefaults.standardUserDefaults().setObject(places, forKey: "places") 
NSUserDefaults.standardUserDefaults().synchronize() 
+0

Спасибо большое, я застрял на том, что на некоторое время –

Смежные вопросы