上一话中地图没能显示,我发现关了Xcode之后一段时间莫名其妙就可以用了,所以有真机还是要用真机调试啊,点开Map按钮,显示如下:
我们想要地图实际起作用,即点击相应餐厅的Map后显示的是餐馆的地理信息,现在要把cell的location信息传给MapViewController,我们在MapViewController中创建存储属性好计算属性用来传值。代码如下:
import UIKit
import MapKit
class MapViewController: UIViewController {
var tempRest: Rest?
var rest : Rest {
set(newRest){
tempRest = newRest
}
get{
return tempRest!
}
}
var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView = MKMapView(frame: self.view.bounds)
self.view.addSubview(mapView)
self.view.backgroundColor = UIColor.orangeColor()
}
地图上要定位要用到经度和纬度,这里就要用到mapView的地理解码,为了能实现真实地定位,我们把第一个cell的地址改成可用的真实地址,代码如下:
if placemarks != nil && placemarks.count > 0 {
let placemark = placemarks[0] as CLPlacemark//向下转型
// 大头针的效果
let annotation = MKPointAnnotation()
annotation.title = self.rest.name
annotation.subtitle = self.rest.type
annotation.coordinate = placemark.location.coordinate
self.mapView.showAnnotations([annotation], animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
则打开的地图显示如下,出不来的小伙伴不要失望,我自己的xcode每次更改地图的设置运行都出不来,要把xcode关了重新打开工程运行,小伙伴们不放也试试。
我们希望在地图的显示中能看到餐厅的图片,那么就需要代理来实现,让MapViewController做自己的代理,首先类要继承MKMapViewDelegate,然后要添加以下代码:
mapView.delegate = self
在成为自己的代理之后要实现代理方法:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let identifier = "MyPin"
var annotionView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if annotionView == nil{
annotionView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotionView.canShowCallout = true
}
let leftCoinView = UIImageView(frame: CGRectMake(0, 0, 47, 47))
leftCoinView.image = UIImage(named: tempRest!.image)
annotionView.leftCalloutAccessoryView = leftCoinView
return annotionView!
}
唯一的不足是我们这个页面是临时展示的,没有返回,所以需要回到DetailViewController中把页面的展示方式编程navigation,之前的代码如下:
func detailTableView(cell: DetailTableViewCell ) {
let mapViewController = MapViewController()
mapViewController.tempRest = rest
self.presentViewController(mapViewController, animated: true, completion: nil)
}
改成如下的代码:
func detailTableView(cell: DetailTableViewCell ) {
let mapViewController:MapViewController = MapViewController()
mapViewController.tempRest = rest
self.navigationController?.pushViewController(mapViewController, animated: true)
}
mapViewController定义的时候一定要声明一下,不然会报错,虽然它在自己的定义中是继承了UIViewController的,但是在push的时候不确定他的类型,效果如下: