本項目是《beginning iOS8 programming with swift》中的項目學習筆記==》所有筆記目錄html
------------------------------------------------------------------------------------------------------------------swift
1. 打開地圖功能:Target-FoodPin-Capabilities-Maps:ON。
2. 在Detail界面的Cell右邊拖一個按鈕,文字爲「Map」,本身設置背景色和字體。
3. 再拖一個控制器到IB,接着拖一個mapKit View進去,連線Map按鈕到新的控制器(push),設置identifier爲:showMap。
4. 去掉多餘的map按鈕:增長一個成員變量mapButton並連線,在建立單元格的地方設置是否顯示mapButton。
5. 增長一個繼承自UIViewController的控制器類MapViewController, import MapKit,設置好成員變量和類的關聯:ide
@IBOutlet weak var mapView: MKMapView!
var restaurant: Restaurant!
6. 實現地址轉座標,並顯示到地圖上:學習
override func viewDidLoad() { super.viewDidLoad() // 將地址字符串轉換成座標 let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(restaurant.location, completionHandler: { (placemarks, error) -> Void in if error != nil { println(error) return } // 取第一個座標 if placemarks != nil && placemarks.count > 0 { let placemark = placemarks[0] as CLPlacemark // 添加Annotation let annotation = MKPointAnnotation() annotation.title = self.restaurant.name annotation.subtitle = self.restaurant.type annotation.coordinate = placemark.location.coordinate self.mapView.showAnnotations([annotation], animated: true) self.mapView.selectAnnotation(annotation, animated: true) } }) }
7. 界面跳轉時傳遞restaurant數據:字體
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showMap" { let destinationController = segue.destinationViewController as MapViewController destinationController.restaurant = self.restaurant } }
8. 給Annotation View加一個圖片spa
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { // placemark和當前地址都是annotation if annotation .isKindOfClass(MKUserLocation) { // 當前地址使用默認的藍色小點表示 return nil } // annotation重用 let identifier = "MyPin" var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) // 設置左側圖片 annotationView.canShowCallout = true let leftIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 47, height: 47)) leftIconView.image = UIImage(named: restaurant.image) annotationView.leftCalloutAccessoryView = leftIconView } return annotationView }