我在这里搜索并看到很多答案,说打开userInteractionEnabled属性。我已经做到了。
我以编程方式创建子视图(不在Interface Builder中)。子视图是UIView的自定义子类(称为PieceSuperClass)。
我想要的只是看起来像
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self.view];
UIView *hitView = [self.view hitTest:currentPosition withEvent:event];
if ([hitView isKindOfClass:[PieceSuperClass class]]) {
return hitView;
}
出于某种原因,hitView
isKindOfClass
UIImageView
即使我绝对将其声明为PieceSuperClass
。 'PieceSuperClass'是UIImageView的子类。
// Draw proper piece
UIImage *pieceImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@.png", pieceColor, pieceName]];
PieceSuperClass *pieceImageView = [[PieceSuperClass alloc] initWithFrame:CGRectMake(0, 0, 39, 38)];
pieceImageView.image = pieceImage;
pieceImageView.identifier = [NSString stringWithFormat:@"%@%@%@", pieceColor, pieceName, pieceNumber];
pieceImageView.userInteractionEnabled = YES;
[boardView addSubview:pieceImageView];
答案 0 :(得分:0)
我认为您正在使用当前位置跟踪错误的视图。如果PieceSuperClass是你的self.view的子视图,你应该跟踪它:
CGPoint currentPosition = [touch locationInView:self.view.subviews];
答案 1 :(得分:0)
最初发生触摸的视图。 (只读)
@property(非原子,只读,保留)UIView * view
因此,您可以知道触摸了哪个视图,只需执行此操作:
UIView *hitView = touch.view;
if ([hitView isKindOfClass:[PieceSuperClass class]]) {
return hitView;
}
答案 2 :(得分:0)
想出来!
- (id)whichPieceTouched:touches withEvent:event
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self.view];
for (int i = 0; i < [piecesArray count]; i++) {
if (CGRectContainsPoint([[piecesArray objectAtIndex:i] frame], currentPosition)) {
return [piecesArray objectAtIndex:i];
}
}
}
虽然我有一个挥之不去的问题:它似乎总是选择下方约20个像素的对象(或下一个对象)。