如果您在跟踪设备位置的同时在 Apple 的 map 应用程序中缩放以放大/缩小,则捏合手势的“平移”组件将被忽略,蓝色位置指示器将固定在屏幕中央。使用普通 MKMapView
时情况并非如此。
假设我已经有了用户的位置,我该如何实现这个效果呢?我已经尝试在委托(delegate)的 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]];
最佳答案
当用户在实际设备(与模拟器相反)上捏合屏幕时,它会导致平移和捏合手势——捏合包含 Action 的“缩放”元素,平底锅包含垂直和水平变化。您需要拦截和阻止平移,这意味着使用 UIPanGestureRecognizer
。
将scrollEnabled
设置为NO
,然后添加一个UIPanGestureRecognizer
来重置中心坐标。该组合将阻止单指平移和捏合的平移组件。
编辑以添加更多细节,在看到您的代码后:touchesMoved:withEvent
在平移已经开始后被调用,因此如果您在那里更改 MKMapView 的中心,你会遇到你所描述的不稳定的渲染问题。您真正需要的是创建一个带有目标操作的 UIPanGestureRecognizer
,如下所示:
UIPanGestureRecognizer *pan = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizePan)] autorelease];
pan.delegate = self;
[self.mapView addGestureRecognizer:pan];
...然后将 didRecognizePan
方法添加到您的 Controller ,并在那里进行中心重置。
关于iphone - 捏 MKMapView 时保持中心坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6006600/