2017-03-24 151 views
1

我已經找到了,並閱讀了大量的博客,以瞭解如何實現我的目標。我遇到的最容易理解的帖子是Pass data back to previous viewcontroller。我確信我的理解混淆了,但是我試圖完成的是在第二個視圖中滑動單元格時從地圖中刪除註釋。Swift 3協議和委託方法?

從CoreData中刪除註釋不是問題,當我單擊rightCallOut時刪除該引腳也不是問題。當我想從VC2中的一個動作中刪除VC1中的地圖上的註釋時,問題就出現了。我在哪裏誤解了這個簡單的過程,我該如何實現它?

FirstViewController

import UIKit 

class ViewController: UIViewController, PinRemoverDelegate { 

    func removePin() { 
     mapView.removeAnnotation(selectedAnnotation) 
    } 

} 

SecondViewController

import UIKit 

protocol PinRemoverDelegate: class { 
    func removePin() 
    } 

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    weak var delegate: PinRemoverDelegate? = nil 

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      let place = storedLocations[indexPath.row] 
      context.delete(place) 
      (UIApplication.shared.delegate as! AppDelegate).saveContext() 

    // Attempt To remove The Pin 
     delegate?.removePin() 
     } 

     tableView.reloadData() 
    } 

} 
+0

'SecondViewController'應該有一個'weak var delegate:PinRemoverDelegate?'屬性,它被設置爲你想發送消息的視圖控制器實例。通常你會在一些擁有或知道兩個視圖控制器的代碼中分配'delegate'。 – par

+0

生病編輯帖子,我已經實施了一個弱變種,我只是在快速複製/縮短代碼粘貼中丟失了它。 – Chilly

+0

記得在你的'FirstViewController'中設置委託爲自己。像'vc2.delegate = self'。這取決於你如何呈現'SecondViewController' – xmhafiz

回答

0

的誤解只是如何去除針。調用removePin函數是錯誤的。只需重新加載CoreData,因爲引腳已經從CoreData中刪除。