I have a MKMapView in a UITableViewCell with user interaction disabled. When I scroll the UITableViewCell it refreshes all of the MKMapViews.
I’ve read the other answers on here, one says to not to use dequeueReusableCellWithIdentifier (I’m not) and the other says to dealloc the mapView (I’m using ARC). I don’t want to use images.
What should I do to prevent the MKMapView from reloading when I scroll my scrollview?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ANFeedCell"];
ANFeedTableViewCell *cell = nil;
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ANFeedTableViewCell" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
MKMapView *mapView = (MKMapView*)[cell viewWithTag:2];
//Takes a center point and a span in miles (converted from meters using above method)
CLLocationCoordinate2D startCoord = CLLocationCoordinate2DMake(37.766997, -122.422032);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:MKCoordinateRegionMakeWithDistance(startCoord, MilesToMeters(0.5f), MilesToMeters(0.5f))];
[mapView setRegion:adjustedRegion animated:YES];
}
return cell;
}
The problem is you are initializing NEW cells for every table cell.
So your MapView get’s reset every time.
This will also lead to memory problems, as a few scrolls up & down the table, will drain your phone’s memory.
Stick to reusable cells, but configure the mapview region every time for the cells.
Here is a good example to get your started:
What is different in this code, is that the mapview is configured each time a cell is displayed, not only when it’s initialized.
Of Course you should change the code to accept the coordinates dynamically from a datasource (i.e. a NSArray).