Быстрые картинки для аннотации
Мне удалось получить пользовательский значок для примечания аннотации в Swift, но теперь я все еще застрял, используя два разных изображения для разных аннотаций. Прямо сейчас кнопка добавляет аннотацию к карте. Должна быть другая кнопка, которая также добавляет аннотацию, но с другим значком.
Есть ли способ использовать reuseId для этого?
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var Map: MKMapView!
@IBAction func btpressed(sender: AnyObject) {
var lat:CLLocationDegrees = 40.748708
var long:CLLocationDegrees = -73.985643
var latDelta:CLLocationDegrees = 0.01
var longDelta:CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, long)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
Map.setRegion(region, animated: true)
var information = MKPointAnnotation()
information.coordinate = location
information.title = "Test Title!"
information.subtitle = "Subtitle"
Map.addAnnotation(information)
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if !(annotation is MKPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"1.png")
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
return anView
}
Ответы
Ответ 1
В методе делегата viewForAnnotation
установите image
, на основе которого annotation
вызывается метод.
Обязательно сделайте это после удаления или создания представления (и не только в части if anView == nil
). В противном случае аннотации, использующие декомпрессированный вид, покажут изображение аннотации, которая ранее использовала представление.
При базовом MKPointAnnotation
один грубый способ разделить аннотации на их title
, но не очень гибкий.
Лучший подход заключается в использовании пользовательского класса аннотаций, который реализует протокол MKAnnotation
(простой способ сделать это для подкласса MKPointAnnotation
) и добавить все свойства, необходимые для реализации пользовательской логики.
В пользовательском классе добавьте свойство, скажем imageName
, которое вы можете использовать для настройки изображения на основе аннотации.
В этом примере подклассы MKPointAnnotation
:
class CustomPointAnnotation: MKPointAnnotation {
var imageName: String!
}
Создайте аннотации типа CustomPointAnnotation
и установите их imageName
:
var info1 = CustomPointAnnotation()
info1.coordinate = CLLocationCoordinate2DMake(42, -84)
info1.title = "Info1"
info1.subtitle = "Subtitle"
info1.imageName = "1.png"
var info2 = CustomPointAnnotation()
info2.coordinate = CLLocationCoordinate2DMake(32, -95)
info2.title = "Info2"
info2.subtitle = "Subtitle"
info2.imageName = "2.png"
В viewForAnnotation
используйте свойство imageName
для установки вида image
:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
let cpa = annotation as CustomPointAnnotation
anView.image = UIImage(named:cpa.imageName)
return anView
}
Ответ 2
iOS Swift Code с помощью Анны и Фабиана Булеге:
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
var info1 = CustomPointAnnotation()
info1.coordinate = CLLocationCoordinate2DMake(26.889281, 75.836042)
info1.title = "Info1"
info1.subtitle = "Subtitle"
info1.imageName = "flag.png"
var info2 = CustomPointAnnotation()
info2.coordinate = CLLocationCoordinate2DMake(26.862280, 75.815098)
info2.title = "Info2"
info2.subtitle = "Subtitle"
info2.imageName = "flag.png"
mapView.addAnnotation(info1)
mapView.addAnnotation(info2)
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
println("delegate called")
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
let cpa = annotation as CustomPointAnnotation
anView.image = UIImage(named:cpa.imageName)
return anView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class CustomPointAnnotation: MKPointAnnotation {
var imageName: String!
}