简体   繁体   English

MKAnnotation Swift

[英]MKAnnotation Swift

I am unsure how to annotate a map in the swift language. 我不确定如何用快速语言注释地图。 I don't know how to create the NSObject class. 我不知道如何创建NSObject类。 The following is code I tried but was unable to run: 以下是我尝试但无法运行的代码:

import Foundation
import MapKit
class MapPin : MKAnnotation
{
    var mycoordinate: CLLocationCoordinate2D
    var mytitle: String
    var mysubtitle: String

    func initMapPin (coordinate: CLLocationCoordinate2D!, title: String!, subtitle: String!)
    {
        mycoordinate = coordinate
        mytitle = title
        mysubtitle = subtitle
    }
}
  1. All initialization methods in Swift must simply be "init" Swift中的所有初始化方法都必须简单地为“init”
  2. MKAnnotation requires that the object inherit from NSObjectProtocol. MKAnnotation要求对象继承自NSObjectProtocol。 To do that, you should have your class inherit from NSObject 要做到这一点,你应该让你的类继承自NSObject
  3. You should declare your properties to match those of the MKAnnotation protocol 您应声明您的属性以匹配MKAnnotation协议的属性
  4. You should not declare your parameters as Implicitly Unwrapped Optionals unless you really have to. 除非确实需要,否则不应将参数声明为Implicitly Unwrapped Optionals。 Let the compiler check if something is nil instead of throwing runtime errors. 让编译器检查某些内容是否为nil而不是抛出运行时错误。

This gives you the result: 这会给你结果:

class MapPin : NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
}

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

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