Update April 11, 2016:
Draw the map and pin programmatically in Swift 2.2 with Xcode 7.3.
Result:
Debug Console:
addSubview(myMap)
addAnnotation
Pin Color Set
=======
Original post October 4, 2014:
import UIKit
Draw the map and pin programmatically in Swift 2.2 with Xcode 7.3.
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let point = MKPointAnnotation()
point.coordinate = CLLocationCoordinate2DMake(25.0305, 121.5360)
point.title = "Taipei"
point.subtitle = "Taiwan"
let myMap = MKMapView(frame: CGRectMake(0,20, view.frame.width, view.frame.height-20))
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dispatch_async(dispatch_get_main_queue()) {
myMap.addAnnotation(point)
print("addAnnotation")
}
}
myMap.centerCoordinate = point.coordinate
myMap.delegate = self
//Span of the map
myMap.setRegion(MKCoordinateRegionMake(myMap.centerCoordinate, MKCoordinateSpanMake(0.2,0.2)), animated: true)
view.addSubview(myMap)
print("addSubview(myMap)")
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView()
annotationView.pinTintColor = UIColor.orangeColor()
print("Pin Color Set")
return annotationView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Result:
Debug Console:
addSubview(myMap)
addAnnotation
Pin Color Set
Simulator:
=======
Original post October 4, 2014:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var myMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
var point = MKPointAnnotation()
self.myMap.delegate = self
point.coordinate = CLLocationCoordinate2DMake(25.0305, 121.5360)
point.title = "Taipei"
point.subtitle = "Taiwan"
myMap.addAnnotation(point)
myMap.centerCoordinate = point.coordinate
myMap.selectAnnotation(point, animated: true)
//Span of the map
myMap.setRegion(MKCoordinateRegionMake(point.coordinate, MKCoordinateSpanMake(0.2,0.2)), animated: true)
println("Span of the map")
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation.isKindOfClass(MKUserLocation)){
return nil
}
var myPin = mapView.dequeueReusableAnnotationViewWithIdentifier("MyIdentifier") as? MKPinAnnotationView
if myPin != nil {
return myPin
}
myPin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "MyIdentifier")
myPin?.pinColor = .Green
return myPin
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When is the mapView function called here?
ReplyDeleteIt is called after addSubview(myMap) and addAnnotation. See my update with Xcode 7.3.
Delete