Ios 无法在Swift中符合MKAnnotation协议
当我尝试符合Ios 无法在Swift中符合MKAnnotation协议,ios,swift,mapkit,mkannotation,Ios,Swift,Mapkit,Mkannotation,当我尝试符合MKAnnotation协议时,它会抛出一个错误:我的类不符合协议MKAnnotation。我正在使用以下代码 import MapKit import Foundation class MyAnnotation: NSObject, MKAnnotation { } Objective-C也可以实现同样的功能。您需要在调用中实现以下必需属性: class MyAnnotation: NSObject, MKAnnotation { var myCoordinate:
MKAnnotation
协议时,它会抛出一个错误:我的类不符合协议MKAnnotation
。我正在使用以下代码
import MapKit
import Foundation
class MyAnnotation: NSObject, MKAnnotation
{
}
Objective-C也可以实现同样的功能。您需要在调用中实现以下必需属性:
class MyAnnotation: NSObject, MKAnnotation {
var myCoordinate: CLLocationCoordinate2D
init(myCoordinate: CLLocationCoordinate2D) {
self.myCoordinate = myCoordinate
}
var coordinate: CLLocationCoordinate2D {
return myCoordinate
}
}
在Swift中,您必须实现协议的每个非可选变量和方法,以符合协议。现在,您的类是空的,这意味着它现在不符合thw
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)
}
您可以看到,如果您至少实现了
坐标
变量,那么您就遵守了协议。下面是一个更简单的版本:
class CustomAnnotation: NSObject, MKAnnotation {
init(coordinate:CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
var coordinate: CLLocationCoordinate2D
}
您不需要将额外的属性var mycoordination:CLLocationCoordinate2D
定义为可接受的答案 或者(在Swift 2.2、Xcode 7.3.1中工作)(注意:Swift不提供自动通知,所以我自己加入。)--
查看此链接,与您提到的问题相同,我已经实现了coordiante属性,尽管我遇到了错误。如果你有任何演示代码,请分享。感谢类MyAnnotation:NSObject,MKAnnotation{var坐标:CLLocationCoordinate2D{get}删除
var坐标:…
定义上方的声明。这只会导致编译器错误并使人困惑。至少在示例中,实现title
和subtitle
也是更好的做法,即使它们是“可选的”(几乎总是需要标题)。感谢示例代码。我怀疑我的问题是:与KVO有关。但是mapView如何观察坐标变化并重新绘制UI呢?
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
}