Swift 2.x cannot set MapView Region

508 Views Asked by At

it's like 5 hours I am stick with this issue. I recently started Swift, cannot say I like it and I get issues after issues. I am trying to do very simple thing. I have class that has date(NSDate), durration(NSTimeInterval), locationName(String) and locationMapView(MKMapView). It doesn't implement any protocol. I want in my initializer to get coordinate and set it to MapView. I found few guides on how to do it but it happens I have problem with basic thing. I cannot even set a region. Here is fragment of init:

    self.locationMapView = MKMapView();

    let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 34.03, longitude: 118.14)
    let span = MKCoordinateSpanMake(100, 80)
    let region = MKCoordinateRegionMake(coordinate, span)
    self.locationMapView!.setRegion(region, animated: true)

    print(String(region))
    print("---")
    print(String(locationMapView!.region))

And here what is displayed in console:

    MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 34.03, longitude: 118.14), span: __C.MKCoordinateSpan(latitudeDelta: 100.0, longitudeDelta: 80.0))
        ---
    MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: nan, longitude: nan), span: __C.MKCoordinateSpan(latitudeDelta: 0.0, longitudeDelta: 0.0))

It took me a while to figure it out that values aren't assigned, but I have no idea why. I found this kind of code in many answers and guides. What is wrong with my implementation?

Thank you everyone for help and I am sorry if this is something stupid.

2

There are 2 best solutions below

0
On

PARTIAL ANSWER:

I have dig a little deeper and I think I have my answer. It seems you cannot assign anything to MKMapView object if it isn't directly connected to display (via outlet).

What I did was removed everything connected with MapView from my class and moved it to UITableViewCell based class which holds outlet to specific MapView. There I was able to assign coordinates and everything worked as intended.

NOTE: You still cannot operate on additional variable like tempMapView and then assign it to actual MapView. It won't work.

I hope I helped people who stumbled on the same problem as I did. If anyone knows why you cannot work with MapView which isn't directly connected to display or how to work it around please let me know.

7
On

The problem is this line:

self.locationMapView = MKMapView();

You created a map view but you didn't assign it a frame. Thus it has zero size. Thus it cannot have a region.