簡體   English   中英

無法在Swift中符合MKAnnotation協議

[英]Unable to conform MKAnnotation protocol in Swift

當我嘗試符合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中,您必須實現協議的每個非可選變量和方法,以符合協議。 現在,你的類是空的,這意味着它現在不符合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變量,那么你就符合協議。

這是一個更簡單的版本:

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

您不需要將額外的屬性var myCoordinate: CLLocationCoordinate2D定義為接受的答案。

或者(適用於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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM