1

我在这里搜索了很多答案,说要打开 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];
4

3 回答 3

0

我认为您正在使用 currectposition 跟踪错误的视图。如果 PieceSuperClass 是您的 self.view 的子视图,您可能应该像这样跟踪它:

CGPoint currentPosition = [touch locationInView:self.view.subviews];
于 2012-12-17T22:11:45.990 回答
0

这来自UITouch 文档

最初发生触摸的视图。(只读)

@property(nonatomic, readonly, retain) UIView *view

所以你可以知道哪个视图被触摸了,然后简单地这样做:

UIView *hitView = touch.view;
if ([hitView isKindOfClass:[PieceSuperClass class]]) {
    return hitView;
}
于 2012-12-17T22:43:29.160 回答
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 像素的对象(或下一个对象)。

于 2012-12-18T00:36:46.657 回答