我在改變MKAnnotationView子類中的圖像視圖時遇到了一些問題。我有一個計時器,根據用戶在某個特定點的位置的數據更新註釋位置。這工作正常,註釋位置正確更新。我這樣做是用下面的代碼:更改MKMapKit MKAnnotation子類中的圖像
[_myAnnotation setCoordinate:point.position];
低於這個,我還計算出用戶是否向東或向西。如果用戶向東行駛,則在類MyAnnotation
上調用setIsMovingRight:YES
方法,而在用戶向西行駛時做相反的操作。
我已經驗證了方法是在正確的時間使用正確的值調用,方法是在方法內部使用NSLog來打印出值的變化。但是,似乎setIsMovingRight
方法對註釋的外觀沒有任何影響。我嘗試在調用方法時將imageview的背景顏色設置爲紅色,但即使這樣也沒有效果。我曾嘗試在各個地方調用setNeedsDisplay而沒有成功。
我可以添加和重新創建一個註釋視圖,但是隻要位置發生變化,註釋就會閃爍,並且看起來確實不太好。
以下是我的自定義註釋視圖「MyAnnotation」的代碼。
@interface MyAnnotation : MKAnnotationView <MKAnnotation>
{
UIImageView *_imageView;
BOOL _currentlyMovingRight;
}
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic,retain) UIImage *image;
-(void)setIsMovingRight:(BOOL)movingRight;
@end
@implementation MyAnnotation
@synthesize coordinate, title, subtitle, image;
-(id)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if(self)
{
_currentlyMovingRight = NO;
_imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
[self addSubview:_imageView];
}
return self;
}
-(void)setIsMovingRight:(BOOL)movingRight
{
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[_imageView setBackgroundColor:[UIColor redColor]]; // THIS LINE NEVER DOES ANYTHING.
if(movingRight && !_currentlyMovingRight)
{
NSLog(@"right now.");
[_imageView setImage:[UIImage imageNamed:@"right.png"]];
}
else if (!movingRight && _currentlyMovingRight)
{
NSLog(@"left now.");
[_imageView setImage:[UIImage imageNamed:@"left.png"]];
}
_currentlyMovingRight = movingRight;
[self addSubview:_imageView];
[self setNeedsDisplay];
}
我會很感激任何人都可以給予的幫助或建議。謝謝!