2

I'm looking for a way to test if a UIView is (partially) obscured by an UIActionSheet, UIAlertView, HUD, etc., or if it is (partially) off the screen in a sliding panel, UIScrollView, etc.. This needs to be a generic solution because there are too many ways to obscure a view.

What comes to mind is to perform a few hit tests at key points where the UIView should be and check how many, if any, hit the given UIView.

Example: Imagine there is no hand in the image below. I'd like to perform a programmatic hit test at the point where the finger is. If View A.2 is not returned, then it is obscured.

touch event

I've looked into hit tests with touch events, but how can I programmatically perform a hit test and see which UIView is hit without physical touch events?

References:

Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94

1 Answers1

0

I found one answer.

First, convert the coordinates of the view you want to perform a hit test on (let's use UIView *testView) to those of the screen coordinates.

CGPoint screenOrigin = 
     [testView.superview convertPoint:testView.frame.origin 
                               toView:nil];

Next, make a couple test hit points (for example, for the upper left and lower right corners of the view). This is an example of one test point.

CGPoint hitTestPoint = CGPointMake(30, screenOrigin.y + 30); // upper left

Then find the top most window* and call hitTest:withEvent: on it. The event can be nil.

UIView *hitTest = [mainWindow hitTest:hitTestPoint withEvent:nil];

Then check if the hitTest result is equal to the testView:

if (testView && [testView isEqual:hitTest] /* && [testView isEqual:hitTest2] */) {
    // The view is not obscured nor off the screen in a sliding panel
}

*Finding the top most window is still an open question, but for most people something like this may work:

UIWindow *mainWindow = [[[UIApplication sharedApplication] windows] firstObject]
Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94