嗨我想在用户点击注释时获取索引号。我有以下代码..
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: )
}
谢谢!
答案 0 :(得分:1)
请尝试以下代码:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation else {
return
}
for (index, item) in LocationList().shop.enumerated() {
if let title = view.annotation?.title {
if item.name! == title! {
print(index)
break
}
}
}
答案 1 :(得分:1)
我认为ShopLocation
已经符合MKAnnotation
,如果没有,那么请使其符合并将其传递给MKAnnotationView
的初始化程序。这将通过delegate
view.annotation
方法中提供
既然您可以访问ShopLocation
个实例,我会想到两个解决方案,可以在shop
符合Equatable
- 这将启用index(of:)
的{{1}}方法(实际上为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.index(of: shopLocation)
// do what you need with the index
}
使用index(where:)
的{{1}}方法(实际上是Array
:)
Collection
就个人而言,我建议采用方法#1,即使Apple建议将值类型符合Equatable。符合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.index(where: { shopLocation in
return // same conditions as for the Equatable
})
// do what you need with the index
}
有助于减少代码,并支持除此处提到的Equatable
之外的许多其他功能。
答案 2 :(得分:0)
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
var index = shops.index(of: view.annotation! as! ShopLocation)!
}
这份工作对我而言。