刚开始 iOS 编程,试图让 UITapGestureRecognizer 使用 iOS 5.1 模拟器工作,但我似乎无法在点击时获得正确的值。这是我从 nathan eror 对 nathan eror 的回答中获取的代码的 How 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。是模拟器的原因吗?还是我做错了什么病态的错误?
P.S 有谁知道如何在发布此问题时将代码突出显示为 objective-C?提前谢谢
最佳答案
我可以重现你的问题。这似乎是因为 [recognizer.view superview]
是窗口(class UIWindow
)。尽管 UIWindow
是 UIView
的子类,但手势识别器似乎无法将位置正确转换为窗口的坐标系。如果我将 subview 添加到 self.view
并将手势识别器放在该 subview 上,它会将点正确转换为 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);
}
但是,窗口的坐标系包含状态栏的空间,并且在您旋转设备时不会旋转。这可能不是您想要的。
关于objective-c - UITapGestureRecognizer 无法在模拟器上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11858342/