刚开始进行iOS编程,试图让UITapGestureRecognizer使用iOS 5.1模拟器工作,点击时似乎无法获得正确的值。这是我从nathan eror对nathan eror的How to add a touch event to a UIView? {/ 3>}的回答中得到的代码
- (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。是因为模拟器吗?还是我做了一些病态的错误?
P.S有谁知道如何在发布此问题时将代码突出显示为Objective-C? thnx提前
答案 0 :(得分: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);
}
但是,窗口的坐标系包括状态栏的空间,并且在旋转设备时不会旋转。这可能不是你想要的。
答案 1 :(得分:0)
尝试NSLog(@“触及点%@”,NSStringFromCGPoint(位置))