在打开Optional值时,意外地发现MKMapView为零

时间:2018-01-10 07:22:30

标签: swift mkmapview

我已经写了这个函数来在地图上绘制叠加层,当我在viewDidLoad的{​​{1}}中调用它时,它正常工作。

MapViewController

我需要使用此函数根据func drawTripLocations(locs: Array<Location>){ var loclist: Array<CLLocationCoordinate2D> = [] if (locs.count > 3){ for loc in locs{ if (loc.gps == 1){ let cord = CLLocationCoordinate2D(latitude: loc.lat!, longitude: loc.lon!) loclist.append(cord) } } } if(loclist != nil && loclist.count > 1){ /* if let overlays = self.mainMapView?.overlays { self.mainMapView.removeOverlays(overlays) self.mainMapView.delegate = self } if let annotations = self.mainMapView?.annotations { self.mainMapView.removeAnnotations(annotations) self.mainMapView.delegate = self }*/ let startmark = loclist.first let endmark = loclist.last let polyline = MKPolyline(coordinates: loclist, count: loclist.count) print(polyline.pointCount) let mapAnnotation = MKPointAnnotation(); self.addDefaultMapPin("Start" , coordinates: startmark!) self.addDefaultMapPin("end" , coordinates: endmark!) self.mainMapView.add(polyline) zoomPolyline(polyline) } } 中的新位置绘制叠加层,因为我在此视图控制器中编写了一个函数:

TableViewController

当我从其他 func getPathLocations(loclist: Array<Location>, stloc: Location, endloc: Location){ var locations: Array<Location> = [] if loclist != nil && loclist.count > 1{ for loc in loclist{ if((Double(loc.tm!) > Double(stloc.tm!) && loc.ign) && (Double(loc.tm!) <= Double(endloc.tm!)) ){ locations.append(loc) } } } print(locations.count) let mainstoryboard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil) let mapViewController: MapViewController = mainstoryboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController mapViewController.drawTripLocations(locs: locations) } 调用此函数时,我遇到的问题是mainMapView drawTripLocations()中的对象始终为nil。

1 个答案:

答案 0 :(得分:2)

是的,因为MapViewController视图尚未加载且mainMapView为nil。按/显示视图控制器时将加载视图。

选项1

访问view

UIViewController属性加载视图
let mainstoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let mapViewController = mainstoryboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController
_ = mapViewController.view // this will make sure view is loaded
mapViewController.drawTripLocations(locs: locations)

选项2 (更好的一个)

MapViewController添加媒体资源

var locations:Array<Location>?

在呈现/推送MapViewController之前设置位置(而不是调用drawTripLocations)。

let mainstoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let mapViewController = mainstoryboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController
mapViewController.locations = locations

以及viewDidLoad

MapViewController方法
override func viewDidLoad() {
    // other code
    if let locations = locations {
        drawTripLocations(locs: locations)
    }
}