【发布时间】:2014-06-12 13:18:45
【问题描述】:
我有一个MKPinAnnotationView 的自定义子类,它显示了一个自定义调用。我想在该注释中处理触摸事件。
我有一个可行的解决方案(如下),但感觉不对。我有一条经验法则,每当我使用 performSelector: .. withDelay: 时,我都是在与系统作斗争,而不是与它一起工作。
对于 MKMapView 的激进事件处理和注释选择处理,是否有人有一个好的、干净的解决方法?
我目前的解决方案:
(我的注释选择类中的所有代码)
我自己进行命中测试(没有这个我的手势识别器不会触发,因为地图视图会消耗事件:
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event; {
// To enable our gesture recogniser to fire. we have to hit test and return the correct view for events inside the callout.
UIView* hitView = nil;
if (self.selected) {
// check if we tpped inside the custom view
if (CGRectContainsPoint(self.customView.frame, point))
hitView = self.customView;
}
if(hitView) {
// If we are performing a gesture recogniser (and hence want to consume the action)
// we need to turn off selections for the annotation temporarily
// the are re-enabled in the gesture recogniser.
self.selectionEnabled = NO;
// *1* The re-enable selection a moment later
[self performSelector:@selector(enableAnnotationSelection) withObject:nil afterDelay:kAnnotationSelectionDelay];
} else {
// We didn't hit test so pass up the chain.
hitView = [super hitTest:point withEvent:event];
}
return hitView;
}
请注意,我还关闭了选择,以便在我覆盖的 setSelected 中我可以忽略取消选择。
- (void)setSelected:(BOOL)selected animated:(BOOL)animated; {
// If we have hit tested positive for one of our views with a gesture recogniser, temporarily
// disable selections through _selectionEnabled
if(!_selectionEnabled){
// Note that from here one, we are out of sync with the enclosing map view
// we're just displaying out callout even though it thinks we've been deselected
return;
}
if(selected) {
// deleted code to set up view here
[self addSubview:_customView];
_mainTapGestureRecogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(calloutTapped:)];
[_customView addGestureRecognizer: _mainTapGestureRecogniser];
} else {
self.selected = NO;
[_customView removeFromSuperview];
}
}
这是我不喜欢的评论 1 的行,但它在 theta 延迟火的末尾也很毛茸茸。我必须返回 superview 链才能到达 mapView,这样我才能说服它选择仍然存在。
// Locate the mapview so that we can ensure it has the correct annotation selection state after we have ignored selections.
- (void)enableAnnotationSelection {
// This reenables the seelction state and resets the parent map view's idea of the
// correct selection i.e. us.
MKMapView* map = [self findMapView];
[map selectAnnotation:self.annotation animated:NO];
_selectionEnabled = YES;
}
与
-(MKMapView*)findMapView; {
UIView* view = [self superview];
while(!_mapView) {
if([view isKindOfClass:[MKMapView class]]) {
_mapView = (MKMapView*)view;
} else if ([view isKindOfClass:[UIWindow class]]){
return nil;
} else{
view = [view superview];
if(!view)
return nil;
}
}
return _mapView;
}
这一切似乎都可以在没有和缺点的情况下工作(就像我从其他解决方案中看到的闪烁一样。它相对简单,但感觉不对。
谁有更好的解决方案?
【问题讨论】:
标签: ios objective-c mkmapview uigesturerecognizer uievent