'Proper way to check if a sub view is outside of the content size of its parent UIScrollView

I have an app that has a UIScrollView with an array of thumbnails for videos. When you touch the thumbnail, the thumbnail begins playing the video. However, when you scroll the view out of visible screen area of the scrollview, the video (obviously) does not stop playing.

I want to be able to detect when the cell goes out of visible screen of the scrollview but I'm not sure what the proper way to observe this change is. I can think of several ways off the top of my head, but I want to do this the "proper" way. How should I go about this?



Solution 1:[1]

I know a method that checks if the one frame is inside the other. I am sure that you can use it in your case, but you need to device your own logic & place it accordingly. A basic outline guide is as follows:

if (CGRectContainsRect(self.view.bounds, videoThumbNailFrame)) {
    // videoThumbnail is Completely Inside
}else 
{

    if (videoThumbNailFrame.origin.y < self.view.bounds.origin.y) {
       //vertically outside 
    }

    if (videoThumbNailFrame.origin.x < self.view.bounds.origin.x) {
      //  horizontally outside
    }
}

May be you can choose to perform this on this delegate method of scrollView. -(void)scrollViewDidEndDecelerating:(UIView *)scrollView

Hope that helps to some extent.

Solution 2:[2]

There are 2 steps:

Objc:-

  • Calculate the visible Rect of the scrollView

      CGRect visibleRect;  
      visibleRect.origin = scrollView.contentOffset;  
      visibleRect.size = scrollView.bounds.size;
    
  • Check if the current playing video frame is intersect with the visibleRect. If YES, just leave it play, if NO, we stop it.

    if( CGRectIntersectsRect( visibleRect, videoFrame ) ) {  
     //do nothing  
    } else {  
     //stop the video  
    } 
    

Swift:-

var visibleRect: CGRect
visibleRect.origin = scrollView.contentOffset
visibleRect.size = scrollView.bounds.size

if visibleRect.intersects(videoFrame) {
//do nothing
} else {
//stop the video
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Balram Tiwari
Solution 2 RsD