1

我正在尝试记录触摸的位置。下面是我的代码。据我了解,在最远的左上角触摸会给我一个 (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));

}
4

3 回答 3

0

Since I cannot comment yet, I have to post an answer. Have you tried setting the background color of the view to a different color so that you can see if its in the top left corner for sure?

于 2012-05-10T19:50:27.337 回答
0

Here's what I have for the view:

@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

And this is the initialization and adding it to a view controller:

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

This works fine for me.

于 2012-05-11T14:59:29.983 回答
0

The -20 offset on the y values is fixed by setting "Status bar is initially hidden" to YES. The rest of the problem looks like it's a hardware issue because I got a different range for x and y values each time I run the program on the iPad. I didn't get this problem while running the program on the simulator. On the simulator, x values range from 1 to 767 and y values range from 1 to 1023, which are pretty correct.

于 2012-05-11T16:15:37.837 回答