简体   繁体   English

在超类符合该协议的子类中实现委托方法Swift

[英]Implementing a Delegate Method in a Subclass whose Superclass conforms to that protocol Swift

I have incorporated the GoogleMaps API into my app and all is well with that. 我已经将GoogleMaps API整合到我的应用程序中,一切都很好。 However after a bit more development I realized I will need to have two different ViewControllers, both showing a GMSMapView but each having slightly different functionality. 但是,经过更多的开发后,我意识到我将需要拥有两个不同的ViewController,两个都显示一个GMSMapView但是每个都有稍微不同的功能。 I decided to make a base class which has the common functionality and that base class conforms to GMSMapViewDelegate . 我决定制作一个具有通用功能且该基类符合GMSMapViewDelegate基类。 In this base class, among other things I have: 在这个基础课中,我有:

class BaseMapViewController: UIViewController {

    var mapView = GMSMapView()

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self

        loadMap()
    }

    func loadMap() {
        mapView = GMSMapView(frame: CGRectZero)
        mapView.mapType = kGMSTypeHybrid
        self.view = mapView
    }
}

extension BaseMapViewController: GMSMapViewDelegate {}

One of the subclasses needs to implement func mapView(mapView: GMSMapView!, didTapAtCoordinate coordinate: CLLocationCoordinate2D) so I just implement that in the subclass (shown below), but it doesn't register any taps. 子类之一需要实现func mapView(mapView: GMSMapView!, didTapAtCoordinate coordinate: CLLocationCoordinate2D)因此我只在子类中实现了该对象(如下所示),但它没有注册任何水龙头。

class SellerMapViewController: BaseMapViewController {

    override func viewDidLoad(){
        super.viewDidLoad()
    }

    func mapView(mapView: GMSMapView!, didTapAtCoordinate coordinate: CLLocationCoordinate2D) {
        print("\(coordinate.latitude,coordinate.longitude)")
    }
}

I then tried putting that delegate method in the base class and it still didn't register any taps. 然后,我尝试将该委托方法放在基类中,但它仍然没有注册任何水龙头。 Any ideas as to what I am doing wrong or what I could try? 关于我在做什么错或可以尝试做什么的任何想法?

Thanks! 谢谢!

It sounds like there could be a couple things going on: 听起来可能发生了几件事:

  • Make sure you are setting the superclass as the delegate, not just conforming to the protocol. 确保将超类设置为委托,而不仅仅是遵守协议。
  • I have done a similar things in my own code, and what I do is implement a dummy function in the superclass that if called prints a message that its subclass needs to implement it, so that the superclass fully implements the delegate method. 我已经在自己的代码中完成了类似的操作,我所要做的是在超类中实现一个虚拟函数,如果调用该函数,则会打印一条消息,表明其子类需要实现它,以便超类完全实现委托方法。
  • Implement the methods that you need to in your subclass. 实现子类中所需的方法。 If the relationship was properly set up in your superclass, the methods will be called in your subclass, overriding the same call in the superclass. 如果在您的超类中正确建立了关系,则将在您的子类中调用这些方法,从而覆盖超类中的相同调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM