2011-05-15 54 views
10

如果捏在苹果的地图应用程序中放大/缩小,跟踪设备的位置,捏手势的“平移”组件将被忽略,蓝色位置指示器保持固定在屏幕。当使用普通的MKMapView时,情况并非如此。保持中心坐标,同时捏MKMapView

假设我已经有用户的位置,我怎么能达到这个效果?我尝试重置代表的regionDid/WillChangeAnimated:方法中的中心坐标,但它们只在手势的开始和结束处被调用。我还尝试添加一个UIPinchGestureRecognizer子类,当触摸移动时重置中心坐标,但这导致呈现毛刺。


编辑:对于那些有兴趣谁,对我下面的作品。

// CenterGestureRecognizer.h 
@interface CenterGestureRecognizer : UIPinchGestureRecognizer 

- (id)initWithMapView:(MKMapView *)mapView; 

@end 

// CenterGestureRecognizer.m 
@interface CenterGestureRecognizer() 

- (void)handlePinchGesture; 

@property (nonatomic, assign) MKMapView *mapView; 

@end 

@implementation CenterGestureRecognizer 

- (id)initWithMapView:(MKMapView *)mapView { 
    if (mapView == nil) { 
    [NSException raise:NSInvalidArgumentException format:@"mapView cannot be nil."]; 
    } 

    if ((self = [super initWithTarget:self action:@selector(handlePinchGesture)])) { 
    self.mapView = mapView; 
    } 

    return self; 
} 

- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer { 
    return NO; 
} 

- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer { 
    return NO; 
} 

- (void)handlePinchGesture { 
    CLLocation *location = self.mapView.userLocation.location; 
    if (location != nil) { 
    [self.mapView setCenterCoordinate:location.coordinate]; 
    } 
} 

@synthesize mapView; 

@end 

然后简单地把它添加到您的MKMapView

[self.mapView addGestureRecognizer:[[[CenterGestureRecognizer alloc] initWithMapView:self.mapView] autorelease]]; 

回答

5

当用户捏住实际设备上的屏幕(与模拟器相反)时,它会导致平移捏合手势 - 捏合包含运动的“缩放”元素,而平移包含垂直和水平的变化。你需要拦截和阻止锅,这意味着使用UIPanGestureRecognizer

scrollEnabled设置为NO,然后添加UIPanGestureRecognizer以重置中心坐标。该组合将阻止双指平移和掐指的平底锅组件。


编辑添加更多细节,并看到你的代码之后:touchesMoved:withEvent被泛称为后已经开始,因此,如果您更改的MKMapView的中心在那里,你会得到herky生涩渲染问题你已经描述过了。你真正需要的是创建一个目标 - 动作一个UIPanGestureRecognizer,像这样:

UIPanGestureRecognizer *pan = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizePan)] autorelease]; 
    pan.delegate = self; 
    [self.mapView addGestureRecognizer:pan]; 

...然后添加一个didRecognizePan方法来你的控制器,做您的中心复位那里。

+0

这导致了与上面提到的相同的渲染问题:地图视图的中心在用户的位置和手势识别器运行其路线的位置之间频繁交替。 也许我误解了你的答案?我已经在这里发布了我的'UIPanGestureRecognizer'子类的实现:http://pastie.org/1934011 – 2011-05-20 23:35:54

+0

这就实现了!我很高兴解决方案非常简单。谢谢,斯科特。 – 2011-05-21 01:59:53

0

只是一个猜测,但你尝试过在regionWillChangeAnimated:开始设置scrollEnabledNO

+0

不幸的是,没有奏效。如果我在开始时(代表方法之外)将其设置为“NO”,则单指平移将被禁用,但捏手势的“平移”组件仍被使用。 – 2011-05-17 21:52:25

0

只是猜测。在regionWillChangeAnimated的开始处:保存当前地图区域,然后使用self.myMapView.region = theSavedRegion或类似方法通过NSTimer持续更新区域。然后在调用regionDidChangeAnimated:时使计时器无效。

但是,您可能会遇到由NSTimer更新区域会导致再次调用regionWillChangeAnimated的问题。

试试看看会发生什么。

+0

我怀疑这会导致与问题中提到的相同的渲染故障;它只是用一个定时器而不是'UIGestureRecognizer'来做同样的事情。如果我取得任何成功,我会调查并报告。 – 2011-05-20 11:57:15

+0

我尝试拦截平底手势时玩了一下,但似乎并不奏效。祝你好运,迫不及待想听听解决方案是什么! – timthetoolman 2011-05-20 18:50:31