0

在一个 ViewController 中工作,它有几个视图作为子视图添加到其中,我有一个 touchesBegan 方法:

    UIImageView *testImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"]];
    testImage.frame = CGRectMake(0, 0, 480, 280);
    [self.view addSubview:testImage];

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point;
    UITouch *touch = [touches anyObject];
    point.x = [touch locationInView:self.view].x;
    point.y = [touch locationInView:self.view].y;

    if ( point.y >= 280 && point.y <= 320 )
    {
        if ( point.x >= 0 && point.x <= 160 )
        {
            [self menu1];
        }

        if ( point.x >= 161 && point.x <= 320 )
        {
            [self menu2];
        }

        if ( point.x >= 321 && point.x <= 480 )
        {
            [self menu3];
        }
    }
}

我的问题是如何在该方法中辨别点击了哪个视图?我一直在使用这些屏幕坐标进行操作,但是如果我在运行时也移动这些视图,那将无法正常工作。

有没有办法从上面查看在触摸或事件或此代码中单击了哪个视图:

UITouch *touch = [touches anyObject];

任何帮助表示赞赏// :)

4

4 回答 4

3

[touch view]将为您提供最初发生触摸的视图(即,即使用户在触摸期间将手指从视图中移开,该视图也将保持不变)。

如果这不是您需要的行为,请使用:

[self.view hitTest:[touch locationInView:self.view] withEvent:event];
于 2009-11-15T02:57:47.797 回答
3

假设您有一个带有这些 ivars 的视图控制器(连接到 Interface Builder 中的控件)

IBOutlet UILabel *label;
IBOutlet UIImageView *image;

要判断触摸是否击中这些项目或背景,请查看将此方法添加到您的视图控制器。

  -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
{  
    UITouch *touch = [[event allTouches] anyObject];

    if ([touch view] == label) {
        NSLog(@"touched the label");
    }

    if ([touch view] == image) {
        NSLog(@"touched the image");
    }

    if ([touch view] == self.view) {
        NSLog(@"touched the background");
    }
}

您想要响应触摸的任何 UIView 子类(如 UIView、UILabel 或 UIImageView)都必须将.userInteractionEnabled属性设置为 YES。

于 2009-11-15T16:20:10.453 回答
1

我可能遗漏了一些东西,但是您的“menuX”元素不会有自己的矩形来描述它们的大小和位置吗?然后你要做的就是询问该点是否在这些矩形内。

于 2009-11-15T02:36:36.833 回答
1

为什么要实施自己的命中测试?只需将透明按钮放置在您想要的任何位置都是微不足道的。

于 2009-11-15T08:10:50.563 回答