触摸位置的值超出了视图的范围

时间:2012-05-10 18:26:07

标签: iphone ios ipad touch

我正在尝试记录触摸的位置。以下是我的代码。据我了解,在最左上角的触摸将给我一个(0,0)的位置,并且非常右下角将是(768,1024)假设我正在拿着iPad的肖像。但是,左上角的值为(-6,-18),右下角的值为(761,1003)。看起来坐标会以某种方式移动。一段self.bounds确实给了我{{0,0},{768,1024}}。谁可以给我解释一下这个?我想得到界限{{0,0},{768,1024}}之间的x和y值。非常感谢你提前。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     CGRect bounds = [self bounds]; 
     NSLog(@"frame: %@", NSStringFromCGRect(bounds)); // this value was traced as frame: {{0, 0}, {768, 1024}}

     UITouch* touch = [[event touchesForView:self] anyObject]; 
     location = [touch locationInView:self];
     NSLog(@"Location: %@", NSStringFromCGPoint(location));

}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
     CGRect bounds = [self bounds]; 

     UITouch* touch = [[event touchesForView:self] anyObject]; 
     location = [touch locationInView:self];
     NSLog(@"Location: %@", NSStringFromCGPoint(location));

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

     CGRect bounds = [self bounds]; 

     UITouch* touch = [[event touchesForView:self] anyObject]; 
     location = [touch locationInView:self];
     NSLog(@"Location: %@", NSStringFromCGPoint(location));

}

3 个答案:

答案 0 :(得分:0)

由于我无法发表评论,我必须发表回答。您是否尝试将视图的背景颜色设置为不同的颜色,以便您可以确定它是否位于左上角?

答案 1 :(得分:0)

以下是我对该观点的看法:

@implementation TouchesView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUserInteractionEnabled:YES];
        [self setBackgroundColor:[UIColor colorWithRed:1.0f green:0.6f blue:0.6f alpha:1.0f]];
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint touch = [[touches anyObject] locationInView:self];
    NSLog(@"(%.1f, %.1f)", touch.x, touch.y);
    NSLog(@"%@", NSStringFromCGPoint(touch));
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{}

@end

这是初始化并将其添加到视图控制器:

TouchesView *touchView = [[TouchesView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:touchView];

这对我来说很好。

答案 2 :(得分:0)

通过将“状态栏最初隐藏”设置为YES,可以修复y值的-20偏移。问题的其余部分看起来像是硬件问题,因为每次在iPad上运行程序时,我都会得到不同的x和y值范围。在模拟器上运行程序时我没有遇到这个问题。在模拟器上,x值的范围是1到767,y值的范围是1到1023,这是非常正确的。