MKAnnotation Swift [英] MKAnnotation Swift
本文介绍了MKAnnotation Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定如何用快速语言注释地图。我不知道如何创建NSObject类。以下是我尝试但无法运行的代码:
I am unsure how to annotate a map in the swift language. I don't know how to create the NSObject class. 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
}
}
推荐答案
- Swift中的所有初始化方法必须只是init
- MKAnnotation要求对象继承自NSObjectProtocol。要做到这一点,你应该让你的类继承自NSObject
- 你应该声明你的属性与MKAnnotation协议的属性相匹配
- 你不应该声明您的参数为隐式展开的选项,除非您真的必须这样做。让编译器检查某些东西是否为nil而不是抛出运行时错误。
- All initialization methods in Swift must simply be "init"
- MKAnnotation requires that the object inherit from NSObjectProtocol. To do that, you should have your class inherit from NSObject
- You should declare your properties to match those of the MKAnnotation protocol
- You should not declare your parameters as Implicitly Unwrapped Optionals unless you really have to. Let the compiler check if something is nil instead of throwing runtime errors.
这会给你结果:
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
}
}
这篇关于MKAnnotation Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文