How to check if a UIView is a subview of a parent view How to check if a UIView is a subview of a parent view objective-c objective-c

How to check if a UIView is a subview of a parent view


an UIView stores its superview and is accessible with the superview-property just try

if([viewB superview]!=nil)    NSLog(@"visible");else    NSLog(@"not visible");

But the better approach is to use the hidden-property of UIView


I went through the same issue and consulted Apple Documentation and came up with this elegant solution:

if([self.childView isDescendantOfView:self.parentView]){    // The childView is contained in the parentView.}


I updated to Swift4, Thanks a lot to @Shinnyx and @thomas.

if viewB.superview != nil{         print("visible")}else{   print("not visible")}

if selfView.isDescendant(of: self.parentView) {    print("visible")}else{    print("not visible")}

func isDescendant(of: UIView)

Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.