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()
}
}
'SecondViewController'应该有一个'weak var delegate:PinRemoverDelegate?'属性,它被设置为你想发送消息的视图控制器实例。通常你会在一些拥有或知道两个视图控制器的代码中分配'delegate'。 – par
生病编辑帖子,我已经实施了一个弱变种,我只是在快速复制/缩短代码粘贴中丢失了它。 – Chilly
记得在你的'FirstViewController'中设置委托为自己。像'vc2.delegate = self'。这取决于你如何呈现'SecondViewController' – xmhafiz