嗨,我想在用户点击注释时获取索引号。我有以下代码..
class ShopLocation: NSObject, MKAnnotation{
var identifier = "Shop location"
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(name:String,lat:CLLocationDegrees,long:CLLocationDegrees,addInfo:String){
title = name
coordinate = CLLocationCoordinate2DMake(lat, long)
subtitle = addInfo
}
}
class LocationList: NSObject {
var shop = [ShopLocation]()
override init(){
shop += [ShopLocation(name:"t1", lat:35.673647,long:139.727686,addInfo:"info")]
shop += [ShopLocation(name:"t2", lat:35.671928,long:139.760815,addInfo:"info")]
shop += [ShopLocation(name:"t3", lat:35.713232,long:139.793467,addInfo:"info")]
}
注释显示在地图上。我想获取索引,例如如果 t1 被点击,我得到的索引为 1。
我不知道写什么
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
LocationList().shop.index(of: )
}
谢谢!
我假设ShopLocation
已经符合MKAnnotation
,如果没有,则使其符合并将其传递给MKAnnotationView
的初始值设定项。这将使其在delegate
方法中可用,通过view.annotation
现在您可以访问该ShopLocation
实例,我想到了两种解决方案,用于在shop
顺应Equatable
-这将使firstIndex(of:)
的方法Array
(实际上是Collection
到Array
符合)
extension ShopLocation: Equatable {
static func ==(lhs: ShopLocation, rhs: ShopLocation) -> Bool {
// place here the conditions for two instances to be equal
}
// ... later in the code
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let shopLocation = view.annotation as? ShopLocation else {
// this early returns if the annotation is not a shop location,
// if you don't wan't that you can use an if-let instead
return
}
let index = LocationList().shop.firstIndex(of: shopLocation)
// do what you need with the index
}
使用firstIndex(where:)
的方法Array
试(实际上的Collection
:)
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let shopLocation = view.annotation as? ShopLocation else {
// this early returns if the annotation is not a shop location,
// if you don't wan't that you can use an if-let instead
return
}
let index = LocationList().shop.firstIndex(where: { shopLocation in
return // same conditions as for the Equatable
})
// do what you need with the index
}
就我个人而言,我建议使用方法 #1,甚至 Apple 也建议使值类型符合 Equatable。符合Equatable
有助于减少代码,并启用除了index(of:)
这里提到的许多其他功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句