1

Is there anyway to check if a view, subview of a view controller, is visible or not right now?

I checked link 1, link 2 and link 3. All these post discussed about UIViewController's view and wrote condition depending on view's window property. But I want to check if a view is visible right now or covered by other view or hidden, which I cannot do with the following condition.

if (viewController.isViewLoaded && viewController.view.window) {
  // viewController is visible
}

Any help about how I can do that? thanks.

Community
  • 1
  • 1
x4h1d
  • 6,042
  • 1
  • 31
  • 46
  • usually you (or your code) should know what is done to the view hierarchy and there-for is visible or in front. can you explain why you need to find it out, so that we are able to suggest better ways? – vikingosegundo Aug 27 '15 at 12:20
  • 1
    my project is a complete mess which was started as cart by previous developers and now in a shape of unicycle, with ferrari style Roof and bonnet. So don't ask. The case is, there is a imageView on a custom view over a view controller :) . I need invoke `bringSubviewToFront:` method for imageView and another custom method only when no other view is over that custom view. – x4h1d Aug 27 '15 at 12:57

2 Answers2

3

A UIView has a superview property and a window property. You can check to see if those are nil. If the view has a nil superview, then it has not been added to anything and is not visible.

If the view does have a superview property that is not nil then you can look at the subviews array property of the superview to determine the stack of views (0 is at the back).

If your view is not at the front of the stack, you would need to look at the frame rects of the other views in front of it to determine if they are covering it. Personally, I would use the CGRectIntersection command to test.

A UIView also has a hidden property which you can check as well as an alpha property which would make the view invisible if it was set to 0.

Walter
  • 5,867
  • 2
  • 30
  • 43
0

You can use this code get the index of the view and decide that it is in front or not

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is 1
Varun Naharia
  • 5,318
  • 10
  • 50
  • 84