0

刚开始 iOS 编程,试图让 UITapGestureRecognizer 使用 iOS 5.1 模拟器工作,我在点击时似乎无法获得正确的值。这是我从 nathan eror 对nathan erorHow to add a touch event to a UIView?的回答中获取的代码。

- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
    CGPoint location = [recognizer locationInView:[recognizer.view superview]];

    NSLog(@"touched points: %g, %g", location.x, location.y);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor blackColor];
    NSLog(@"gets in here");
    UITapGestureRecognizer *singleFingerTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:singleFingerTap];
}

每次我在模拟器上点击我的 macbook pro 上的触控板时,我的值都会得到 0.000000。是因为模拟器吗?还是我做错了什么?

PS有谁知道如何在发布这个问题时将代码突出显示为objective-C?提前谢谢

4

2 回答 2

2

我可以重现你的问题。它似乎发生是因为[recognizer.view superview]是窗口(类UIWindow)。虽然UIWindow是 的子类UIView,但手势识别器似乎无法正确地将位置转换为窗口的坐标系。如果我添加一个子视图self.view并将手势识别器放在该子视图上,它会将点self.view正确转换为 的坐标系。

我建议您在http://bugreport.apple.com提交错误报告。(产品为“iPhone SDK”。)

如果您确实需要获取窗口坐标系中的点,可以这样做:

- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
    CGPoint location = [recognizer locationInView:recognizer.view];
    location = [recognizer.view convertPoint:location toView:recognizer.view.superview];

    NSLog(@"touched point: %g, %g", location.x, location.y);
}

但是,窗口的坐标系包括状态栏的空间,并且在您旋转设备时不会旋转。这可能不是你想要的。

于 2012-08-08T06:05:55.373 回答
0

试试 NSLog(@"touched point %@", NSStringFromCGPoint(location))

于 2012-08-08T05:55:24.513 回答