2009-10-03 2 views
1

У меня возникла проблема с представлениями аннотаций в MapKit на iPhone. Мне удается рисовать пользовательские аннотации на карте - никаких проблем нет. Мне даже удается перерисовать их после перетаскивания или масштабирования. Однако бывают случаи, когда перерисовка не работает: примером может быть двойной щелчок.Проблема с аннотацией Просмотры исчезает при двойном нажатии zoom

Прилагаю некоторый код, в котором я рисую несколько прямоугольников в определенных местах на карте, и когда я увеличиваю масштаб с помощью жестов двух пальцев, все работает нормально (т. Е. Прямоугольники перерисовываются). Однако, когда я дважды нажимаю, прямоугольники исчезают. Еще страннее то, что все методы вызываются в том порядке, в котором они должны быть, и, в конце концов, даже вызов drawRect вызывается, но прямоугольники не нарисованы.

Так вот код, пожалуйста, попробуйте сами - два пальца масштабирования работает, но двойное нажатие трансфокации не делает:

PlaygroundViewController.h

#import <UIKit/UIKit.h> 
#import <MapKit/MapKit.h> 

@interface PlaygroundViewController : UIViewController <MKMapViewDelegate>{ 
MKMapView *mapView_; 
NSMutableDictionary* myViews_; 
} 

@end 

PlaygroundViewController.m

#import "PlaygroundViewController.h" 
#import "Territory.h" 
#import "TerritoryView.h" 

@implementation PlaygroundViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
mapView_=[[MKMapView alloc] initWithFrame:self.view.bounds]; 
[self.view insertSubview:mapView_ atIndex:0]; 
mapView_.delegate = self; 
[mapView_ setMapType:MKMapTypeStandard]; 
    [mapView_ setZoomEnabled:YES]; 
    [mapView_ setScrollEnabled:YES]; 
myViews_ = [[NSMutableDictionary alloc] init]; 
for (int i = 0; i < 10; i++) { 
    Territory *territory; 
    territory = [[[Territory alloc] init] autorelease]; 
    territory.latitude_ = 40 + i; 
    territory.longitude_ = -122 + i; 
    [mapView_ addAnnotation:territory]; 

} 
} 

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { 
MKAnnotationView* territoryView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"Territory"]; 
if (!territoryView){ 
    territoryView = [[[TerritoryView alloc] initWithAnnotation:annotation reuseIdentifier:@"Territory"] autorelease]; 
    Territory* currentTerritory = (Territory*) annotation; 
    [myViews_ setObject:territoryView forKey:currentTerritory.territoryID_]; 
} 
    else{ 
    territoryView.annotation = annotation; 
} 
return territoryView; 
} 

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { 
for (NSObject* key in [myViews_ allKeys]) { 
    TerritoryView* territoryView = [myViews_ objectForKey:key]; 
    [territoryView initRedraw]; 
} 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 

- (void)dealloc { 
    [super dealloc]; 
} 

Territory.h

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 


@interface Territory : NSObject <MKAnnotation> { 
float latitude_; 
float longitude_; 
NSString* territoryID_; 
} 

@property (nonatomic) float latitude_; 
@property (nonatomic) float longitude_; 
@property (nonatomic, retain) NSString* territoryID_; 


@end 

Territory.m

#import "Territory.h" 

@implementation Territory 

@synthesize latitude_; 
@synthesize longitude_; 
@synthesize territoryID_; 


- (CLLocationCoordinate2D)coordinate { 
CLLocationCoordinate2D coord_ = {self.latitude_, self.longitude_}; 
return coord_; 
} 

-(id) init { 
if (self = [super init]) { 
    self.territoryID_ = [NSString stringWithFormat:@"%p", self]; 
} 
return self; 
} 


@end 

TerritoryView.h

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 

@interface TerritoryView : MKAnnotationView { 

} 

- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier; 
- (void)initRedraw; 

@end 

TerritoryView.m

#import "TerritoryView.h" 

@implementation TerritoryView 

- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier { 
    if ([super initWithAnnotation:annotation reuseIdentifier:@"Territory"]) { 
    self.initRedraw; 
    } 
    return self; 
} 

- (void)initRedraw { 
self.frame = CGRectMake(0,0,40,40); 
[self setNeedsDisplay]; 
} 

- (void)drawRect:(CGRect)rect { 
NSLog(@"in draw rect"); 
} 

@end 

Любая помощь приветствуется. Вот заархивированный проект: link

+0

Пожалуйста, отправьте почтовый проект. –

+0

ok, добавлена ​​ссылка на zip-проект в конце сообщения. –

ответ

0

Имейте в виду, что начало кадра находится в системе координат его родителя, поэтому установка его на ноль, вероятно, отключает экран. Я подозреваю, что причина, по которой она когда-либо срабатывает, заключается в том, что она сбрасывается за вашей спиной в большинстве ситуаций, но не в тех, где она терпит неудачу.

заменить: self.frame = CGRectMake (0,0,40,40);

с: self.frame = CGRectMake (self.frame.origin.x, self.frame.origin.y, 40,40);