【问题标题】:Unable to conform MKAnnotation protocol in Swift无法在 Swift 中遵循 MKAnnotation 协议
【发布时间】:2015-03-27 12:21:59
【问题描述】:

当我尝试遵守 MKAnnotation 协议时,它会抛出错误,我的类不符合协议 MKAnnotation。我正在使用以下代码

import MapKit
import Foundation

class MyAnnotation: NSObject, MKAnnotation
{

}

Objective-C 也可以做到这一点。

【问题讨论】:

标签: ios swift mapkit mkannotation


【解决方案1】:

您需要在调用中实现以下必需属性:

class MyAnnotation: NSObject, MKAnnotation {
    var myCoordinate: CLLocationCoordinate2D

    init(myCoordinate: CLLocationCoordinate2D) {
        self.myCoordinate = myCoordinate
    }

    var coordinate: CLLocationCoordinate2D { 
        return myCoordinate
    }
}

【讨论】:

  • 正如你提到的,我已经实现了 coordiante 属性,尽管我遇到了错误。如果您有任何演示代码,请分享。谢谢 class MyAnnotation: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D { get } }
  • 删除class... 定义上方的var coordinate:... 声明。这只会导致编译器错误并使人们感到困惑。至少在示例中,实现titlesubtitle 也是更好的做法,即使它们是“可选的”(几乎总是需要标题)。
【解决方案2】:

在 Swift 中,您必须实现协议的每个非可选变量和方法以符合协议。现在,你的类是空的,这意味着它现在不符合MKAnnotation 协议。如果你看MKAnnotation的声明:

protocol MKAnnotation : NSObjectProtocol {

    // Center latitude and longitude of the annotation view.
    // The implementation of this property must be KVO compliant.
    var coordinate: CLLocationCoordinate2D { get }

    // Title and subtitle for use by selection UI.
    optional var title: String! { get }
    optional var subtitle: String! { get }

    // Called as a result of dragging an annotation view.
    @availability(OSX, introduced=10.9)
    optional func setCoordinate(newCoordinate: CLLocationCoordinate2D)
}

您可以看到,如果您至少实现了coordinate 变量,那么您就符合协议。

【讨论】:

    【解决方案3】:

    这是一个更简单的版本:

    class CustomAnnotation: NSObject, MKAnnotation {
        init(coordinate:CLLocationCoordinate2D) {
            self.coordinate = coordinate
            super.init()
        }
        var coordinate: CLLocationCoordinate2D
    }
    

    您不需要将额外的属性 var myCoordinate: CLLocationCoordinate2D 定义为接受的答案。

    【讨论】:

      【解决方案4】:

      或者(适用于 Swift 2.2、Xcode 7.3.1)(注意:Swift 不提供自动通知,所以我自己添加。)--

      import MapKit
      
      class MyAnnotation: NSObject, MKAnnotation {
      
      // MARK: - Required KVO-compliant Property  
      var coordinate: CLLocationCoordinate2D {
          willSet(newCoordinate) {
              let notification = NSNotification(name: "MyAnnotationWillSet", object: nil)
              NSNotificationCenter.defaultCenter().postNotification(notification)
          }
      
          didSet {
              let notification = NSNotification(name: "MyAnnotationDidSet", object: nil)
              NSNotificationCenter.defaultCenter().postNotification(notification)
          }
      }
      
      
      // MARK: - Required Initializer
      init(coordinate: CLLocationCoordinate2D) {
          self.coordinate = coordinate
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多