Question

My viewcontroller supports landscape orientation only. I have added a white colored view(whiteView - IBOutlet in xib) inside the main view, and added a blue colored CALayer(blueLayer - property in class) inside the whiteview. When I run a hitTest on this viewcontroller, it returns incorrect results on touches on the right side of the app window, everything works fine on the left side. It is as if the app is running in a portrait mode even though the current orientation is landscape. Everything works fine in portrait mode.

Below is the code. In landscape every touch towards the right returns "Touch in main view". What do I need to do to make it work correctly in landscape?

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.blueLayer = [[CALayer alloc] init];
    CGRect frame = self.whiteView.frame;
    self.blueLayer.frame = CGRectMake(20.0, 20.0, frame.size.width-40.0, frame.size.height - 40.0f);
    self.blueLayer.backgroundColor = [UIColor blueColor].CGColor;
    [self.whiteView.layer addSublayer:self.blueLayer];
}

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

    CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Touch in main view" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    CALayer *touchedLayer = [self.view.layer hitTest:touchPoint];

    if(touchedLayer == self.blueLayer){
        alertView.message = @"Touch in blue view";
    }
    else if (touchedLayer == self.whiteView.layer){
        alertView.message = @"Touch in white view";
    }
    else
        alertView.message = @"Touch in main view";

    [alertView show];
}
Was it helpful?

Solution

It has nothing to do with orientation. According to apple docs, "hitTest Returns the farthest descendant of the layer". Siblings are searched in top-to-bottom order. the touch point is in the coordinate system of the receiver's superlayer. So add this line immediately after you get the touchPoint. i.e

CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
touchPoint = [self.view.layer convertPoint:touchPoint toLayer:self.view.layer.superlayer];
...........
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top