Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MKAnnotation Swift

Tags:

ios

swift

iphone

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     } } 
like image 436
BDGapps Avatar asked Jun 15 '14 20:06

BDGapps


People also ask

What is MKAnnotation?

An interface for associating your content with a specific map location.

What is mapview annotation?

Derived from the MKAnnotationView class, an annotation view draws the visual representation of the annotation on the map surface. Register annotation views with the MKMapView so the map view can create and efficiently reuse them.

What is MKMapView?

The MKMapView class supports the ability to annotate the map with custom information. Because a map may have large numbers of annotations, map views differentiate between the annotation objects used to manage the annotation data and the view objects for presenting that data on the map.


1 Answers

  1. All initialization methods in Swift must simply be "init"
  2. MKAnnotation requires that the object inherit from NSObjectProtocol. To do that, you should have your class inherit from NSObject
  3. You should declare your properties to match those of the MKAnnotation protocol
  4. 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.

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     } } 
like image 190
drewag Avatar answered Sep 27 '22 20:09

drewag