我有一个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 延迟火灾结束时它也很毛茸茸。我必须走回超级视图链才能到达 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;
}
这一切似乎在没有和缺点的情况下都有效(就像我从其他解决方案中看到的闪烁一样。它相对简单,但感觉不对。
有人有更好的解决方案吗?