Search code examples
iosuiviewuiwindowhittest

Why doesn't hitTest return the view attached to the window?


Can someone spend a second and give me a pointer please?

I've got a UIView attached to a UIWindow, and I'm playing with hitTesting of points (for reasons that are much more complex than I want to get into here).

Given a view attached as a sub view of a window, I would expect that hitTest would find the view, but it doesn't appear to:

- (void)test_hitTest_shouldFindTheViewAttachedToAWindow {
    UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 210, 520)];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 20, 200, 500)];
    [window addSubview:view];

    // This is ok
    GHAssertEquals([view hitTest:CGPointMake(110, 270) withEvent:nil], view, nil);

    // This fails: why? I would expect it to return the view, but it return null.
    GHAssertEquals([view.window hitTest:CGPointMake(110, 270) withEvent:nil], view, nil);
}

The point is clearing inside the bounds of the window, right? Why doesn't it find the view?


Solution

  • UIWindow is created invisible by default, which means hitTest:withEvent will ignore it. If you set view.window.hidden = NO then hitTest:withEvent will work as you expect it to.